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:
 
 
 
  
  - <? Php
- Echo mb_substr ('in this way, my strings will not contain garbled characters such as ^_^', 0, 7, 'utf-8 ');
- ?>
- Output: in this way, my words
- <? Php
- Echo mb_strcut ('in this way, my strings will not contain garbled characters such as ^_^', 0, 7, 'utf-8 ');
- ?>
 
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
 
 
 
 
  
  - function GBsubstr($string, $start, $length) {  
- if(strlen($string)>$length){  
- $str=null;  
- $len=$start+$length;  
- for($i=$start;$i<$len;$i++){  
- if(ord(substr($string,$i,1))>0xa0){  
- $str.=substr($string,$i,2);  
- $i++;  
- }else{  
- $str.=substr($string,$i,1);  
- }  
- }  
- return $str.'...';  
- }else{  
- return $string;  
- }  
- }  
 
The above two code examples are the reasons for garbled characters when PHP substr intercepts Chinese characters and solutions.