Let's take a look at how to use PHP custom functions to intercept the length of the character we want to intercept, beyond the ellipsis to replace or hide it.
String Truncation Method:
//intercept string length function cut ($Str, $Length, $more =true) {//$STR to intercept string, $ Length is the global $s that needs to be intercepted; $i = 0; $l = 0; $ll = strlen ($STR); $s = $Str; $f = true; while ($i <= $ll) {if (ord ($Str {$i}) < 0x80) {$l + +; $i + +; } else if (Ord ($Str {$i}) < 0xe0) {$l + +; $i + = 2; } else if (Ord ($Str {$i}) < 0xf0) {$l + = 2; $i + = 3; } else if (Ord ($Str {$i}) < 0xf8) {$l + = 1; $i + = 4; } else if (Ord ($Str {$i}) < 0XFC) {$l + = 1; $i + = 5; } else if (Ord ($Str {$i}) < 0xFE) {$l + = 1; $i + = 6; } if (($l >= $Length-1) && $f) {$s = substr ($Str, 0, $i); $f = false; } if (($l > $Length) && ($i < $ll) && $more) {$s = $s. '...'; Break If intercepted, the end of the string is appended with the ellipsis "..."} } return $s;}
How to use:
$str = ' Take a look at where to intercept? '; Echo Cut ($STR, 1); Echo '
'; Echo Cut ($STR, 4); Echo '
'; Echo Cut ($str, 5); Echo '
'; Echo Cut ($str, 5,false); Echo '
'; $str = ' Mix English and Chinese to see hello? '; Echo Cut ($STR), Echo '
'; Echo Cut ($STR, 50);
Output:
See... Look... Look... Look at the mix of Chinese and English to see Hel ... A mix of Chinese and English look hello?
Explanation: The general UTF-8 format is 3 bytes, while GBK compatible gb2312 is generally 2 bytes, the above is UTF-8 encoded as an instance.
The third parameter, $more, allows you to toggle the ellipsis pattern, which is true with an ellipsis and false to no ellipsis.