Phpsubstr Chinese garbled solution if substr is directly used to intercept Chinese strings, it will certainly produce garbled characters, because it will divide a Chinese character into half. why is it like this? due to internal machine encoding problems, now let's look at the solution
1. 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 the string is intercepted only for the output, it can be implemented as follows: substr ($ str, 0, 30). chr (0 ).
The PHP instance code is as follows:
* Chinese characters can be intercepted without garbled characters
* The parameter $ str is a string, $ start is the start character, and $ len is the end character.
* Returns the truncated characters.
*/
Function msubstr ($ str, $ start, $ len ){
$ Tmpstr = ""; // open-source phpfensi.com
$ Strlen = $ start + $ len;
For ($ I = 0; $ I <$ strlen; $ I ++ ){
If (ord (substr ($ str, $ I, 1)> 0xa0 ){
$ Tmpstr. = substr ($ str, $ I, 2 );
$ I ++;
} Else
$ Tmpstr. = substr ($ str, $ I, 1 );
}
Return $ tmpstr;
}
Method 2: php implements the method of intercepting Chinese strings without garbled characters. the code is as follows:
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;
}
}
?>