PHP Notes | Mixed string interception in English
It is often necessary to intercept long content when a list of records is displayed on a Web page.
Using PHP built-in substr function on the Chinese and English mixed strings, especially the character encoding in the case of UTF-8, support is very bad, will appear garbled.
So I wrote a function:
?
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). "...";}
?
Tested successfully. yeah!
?
=======================================================================
2012-06-15 Update:
?
Once again today, the benefit is that the two English characters will be treated as a character length:
So 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;}