PHP comes with several string truncation functions, including substr and mb_substr. When the former is processing Chinese characters, GBK is two length units, and UTF is three length units. after encoding is specified, a Chinese character is one length unit. PHP comes with several string truncation functions, including substr and mb_substr. When the former is processing Chinese characters, GBK is two length units, and UTF is three length units. after encoding is specified, a Chinese character is one length unit.
Mb_substr usage
string mb_substr( string$str, int$start[, int$length[, string$encoding]] );
Mb_substr: number of characters based on the multi-byte-safe substr () operation. Start from str. The first character is 0. The second character is 1, and so on:
The master string intercepted by str.
Start position.
The maximum length of the string returned by length. if it is omitted, it is truncated to the end of str.
The encoding parameter is character encoding. If omitted, internal character encoding is used.
We can use the following code to solve this problem.
$mess=mb_substr($message,0,19,'gb2312');
Gb2312 is the Chinese encoding format.
Mb_substr
Substr sometimes intercepts 1/3 Chinese or half Chinese characters, and garbled characters are displayed. mb_substr is more suitable for use. However, sometimes mb_substr is not so easy to use. For example, I want to display the brief information of a small image. five Chinese characters are exactly the same. if there are more than five Chinese characters, I will take the first four and add "…". It is okay to process Chinese in this way, but it is too short to process English or numbers. Use the following function to solve this problem:
= 224) {$ c = 3; $ t = substr ($ str, $ I, $ c); $ l + = 2;} elseif (ord ($ t)> = 192) {$ c = 2; $ t = substr ($ str, $ I, $ c); $ l + = 2;} else {$ c = 1; $ l ++;} // $ t = substr ($ str, $ I, $ c); $ I + = $ c; if ($ l> $ len) break; $ a [] = $ t;} $ re = implode ('', $ a); if (substr ($ str, $ I, 1 )! = False) {array_pop ($ a); ($ c = 1) and array_pop ($ a); $ re = implode ('', $ ); $ dot and $ re. = '... ';} return $ re ;}}