Php Chinese character string truncation garbled problem solution in fact the following method 1 and 2 are not recommended now. readers should learn more after reading it. some netizens leave a message, in fact, php has a ready-made mb_substr for multi-byte security string truncation function,
Reference: http://www.php.net/manual/zh/function.mb-substr.php
Http://baike.baidu.com/view/4517800.htm
Method 1: string encoded as UTF-8, a Chinese character occupies three bytes:
Public static function chinesesubstr ($ str, $ start, $ len) {// $ str indicates the string, and $ start indicates the start position of the string, $ len indicates the string length $ strlen = $ start + $ len; // use $ strlen to store the total length of the string, that is, from the starting position of the string to the total length of the string for ($ I = $ start; $ I <$ strlen;) {if (ord (substr ($ str, $ I, 1)> 0xa0) {// if the ASCII order value of the first byte in the string is greater than 0xa0, it indicates the Chinese character $ tmpstr. = substr ($ str, $ I, 3); // each time a three-character string is taken out and assigned to the variable $ tmpstr, that is, a Chinese character $ I = $ I + 3; // variable auto-Increment 3} else {$ tmpstr. = substr ($ str, $ I, 1); // if it is not a Chinese character, a character is taken out each time and assigned to the variable $ tmpstr $ I ++;} return $ tmpstr; // return string}
Method 2: encode the string as GB2312. a Chinese character occupies two bytes:
Public static function chinesesubstr ($ str, $ start, $ len) {// $ str indicates the string, and $ start indicates the start position of the string, $ len indicates the string length $ strlen = $ start + $ len; // use $ strlen to store the total length of the string, that is, from the starting position of the string to the total length of the string for ($ I = $ start; $ I <$ strlen;) {if (ord (substr ($ str, $ I, 1)> 0xa0) {// if the ASCII order value of the first byte in the string is greater than 0xa0, it indicates the Chinese character $ tmpstr. = substr ($ str, $ I, 2); // each time two characters are taken out and assigned to the variable $ tmpstr, that is, a Chinese character $ I = $ I + 2; // variable auto-Increment 2} else {$ tmpstr. = substr ($ str, $ I, 1); // if it is not a Chinese character, a character is taken out each time and assigned to the variable $ tmpstr $ I ++;} return $ tmpstr; // return string}