PHP comes with several string interception functions, which are commonly used in substr and MB_SUBSTR. The former in the processing of Chinese, GBK is 2 units of length, UTF is 3 units of length, the latter is specified after encoding, a Chinese is 1 length units.
MB_SUBSTR usage
String Mb_substr (String$str, int$start[, int$length[, string$encoding]);
MB_SUBSTR performs a multi-byte secure substr () operation based on the number of characters. Calculated from the starting position of Str. The position of the first character is 0. The position of the second character is 1, and so on:
The truncated female string of Str.
Start position.
The length of the string returned by length, if omitted, is truncated to the end of Str.
The encoding parameter is a character encoding. If omitted, the internal character encoding is used.
Then we can use the code to complete the problem.
$mess =mb_substr ($message, 0,19, ' gb2312 ');
GB2312 is the Chinese encoding format.
MB_SUBSTR processing mixed strings in English and Chinese
Substr sometimes cut 1/3 Chinese or half of Chinese, will show garbled, relatively speaking mb_substr more suitable for us to use. But sometimes mb_substr doesn't look so good. For example, I want to display a small picture of the brief information, 5 Chinese exactly, more than 5 to intercept the top 4 Plus "...", so the Chinese is no problem, but to deal with English or numbers, so the interception is too short. The following function is used to solve this problem:
<?php/*** String Intercept * * @author gesion* @param string $str Original String * @param int $len intercept Length (Chinese/full-width symbols default to 2 units, English/numeric is 1.) * For example: Length 12 indicates 6 Chinese or full-width characters or 12 English or numeric) * @param bool $dot If the string exceeds the $len length, then add "...") * @return Strin G*/class onens {public static function G_substr ($str, $len = N, $dot = true) {$i = 0; $l = 0; $c = 0; $a = array (); while ($l < $len) {$t = substr ($str, $i, 1); if (Ord ($t) >= 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 (' ', $a); $dot and $re. = ' ... '; } return $re; }}