PHP intercepts strings in utf-8 format

Source: Internet
Author: User
This article mainly introduces the PHP interception utf-8 format string Instance code of the relevant data, and attached to the example code, the need for friends can refer to the following

PHP intercepts strings in utf-8 format

In PHP, we often need to intercept strings. English characters occupy one byte, Chinese characters occupy two bytes, but Chinese characters occupy two bytes is relative to GBK encoding but in the current international popular UTF8 encoding, a Chinese character occupies 3 bytes. This article introduces you to PHP's function of intercepting utf-8 format strings.

To illustrate:

function truncate_utf8_string ($string, $length, $etc = ' ... ') {$result = '; $string = Html_entity_decode (Trim (strip_ tags ($string)), ent_quotes, ' UTF-8 '); $strlen = strlen ($string); for ($i = 0; (($i < $strlen) && ($length > 0)); $i + +) {if ($number = Strpos (Str_pad (Decbin (substr ($string, $i, 1)), 8, ' 0 ', str_pad_left), ' 0 ')) {
  if ($length < 1.0) {break  ;  }  $result. = substr ($string, $i, $number);  $length-= 1.0;  $i + = $number-1; } else {  $result. = substr ($string, $i, 1);  $length-= 0.5; }} $result = Htmlspecialchars ($result, ent_quotes, ' UTF-8 '); if ($i < $strlen) {$result. = $etc;} return $result;}

If you need to intercept a string in utf-8 format, call this function directly.

<?php  $str = "Call this function directly if you need to intercept a string in utf-8 format." ";  Echo truncate_utf8_string ($STR, 10);//Output result: If you need to intercept utf-8 ...? >

The above is the whole content of this article, I hope that everyone's study has helped.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.