PHP substr intercepts Chinese characters and garbled characters

Source: Internet
Author: User

We are using1. Use mb_substr of the mbstring extension library to intercept the database without garbled characters.

2. Write the truncation function by yourself, but it is not as efficient as using the mbstring extension library.

3. If you only want to output the intercepted string, use the following method: substr ($ str, 0, 30). chr (0 ).

The substr () function can split text. However, if the text to be split contains Chinese characters, you can use the mb_substr ()/mb_strcut function, mb_substr () the usage of/mb_strcut is similar to that of substr (), but an additional parameter must be added at the end of mb_substr ()/mb_strcut to set the character string encoding. However, php_mbstring.dll is not enabled on the server, in php. ini opens php_mbstring.dll.

For example, PHP substr intercepts Chinese characters:

 
 
  1. <? Php
  2. Echo mb_substr ('in this way, my strings will not contain garbled characters such as ^_^', 0, 7, 'utf-8 ');
  3. ?>
  4. Output: in this way, my words
  5. <? Php
  6. Echo mb_strcut ('in this way, my strings will not contain garbled characters such as ^_^', 0, 7, 'utf-8 ');
  7. ?>

Output:
From the above example, we can see that mb_substr is used to split characters by words, while mb_strcut is used to split characters by bytes, but it does not produce half a character.

PHP substr intercepts Chinese characters without garbled characters

 
 
  1. function GBsubstr($string, $start, $length) {  
  2. if(strlen($string)>$length){  
  3. $str=null;  
  4. $len=$start+$length;  
  5. for($i=$start;$i<$len;$i++){  
  6. if(ord(substr($string,$i,1))>0xa0){  
  7. $str.=substr($string,$i,2);  
  8. $i++;  
  9. }else{  
  10. $str.=substr($string,$i,1);  
  11. }  
  12. }  
  13. return $str.'...';  
  14. }else{  
  15. return $string;  
  16. }  
  17. }  

The above two code examples are the reasons for garbled characters when PHP substr intercepts Chinese characters and solutions.


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.