PHP note | intercept between Chinese and English strings. it is often necessary to intercept too long content when the record list is displayed on the WEB page. Use PHP built-in substr function for English and Chinese mixed strings, especially character encoding in the case of UTF-8, support is very bad, will appear garbled. So I wrote a function :? Functiontru PHP note | intercept between Chinese and English strings
When the record list is displayed on the WEB page, the content that is too long must be intercepted.
Use PHP built-in substr function for English and Chinese mixed strings, especially character encoding in the case of UTF-8, support is very bad, will appear garbled.
So I wrote a function myself:
?
function truncate($string, $len, $wordsafe = FALSE) {$slen = strlen($string);if ($slen <= $len) {return $string;}if ($wordsafe) {while (($string[-- $len] != ' ') && ($len > 0)) {};}if ((ord($string[$len]) < 0x80) || (ord($string[$len]) >= 0xC0)) {return substr($string, 0, $len) . "...";}while (ord($string[-- $len]) < 0xC0) {};return substr($string, 0, $len) . "...";}
?
The test was successful. YEAH!
?
========================================================== ====================================
Updated on:
?
I wrote another one today. The advantage is that two English characters are treated as the length of one Chinese character:
Therefore, the length of the number of Chinese characters to be intercepted
?
?
function truncate($string, $len, $cnCharWidth = 2) {$len = $len * $cnCharWidth;$suffix = "...";$newStr = "";for ($i = 0, $j = 0; $i < $len; $i++, $j++) {if (!isset($string[$j])) {$suffix = "";break;}$start = $j;while ($j < ($start +3) && !(ord($string[$j]) < 0x80)) {$j++;}if ($start == $j) {$charLen = 1;}else {$i = $i + 1;$j--;$charLen = 3;}$newStr .= substr($string, $start, $charLen);}return $newStr . $suffix;}