Home >Backend Development >PHP Tutorial >PHP string interception length custom method
Let’s introduce below how to use PHP custom function to intercept the length of characters we want to intercept, and use ellipsis to replace or hide the excess part.
String interception method:
//截取字符串长度 function cut($Str, $Length,$more=true) { //$Str为截取字符串,$Length为需要截取的长度 global $s; $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; //如果进行了截取,字符串末尾加省略符号“...” } } return $s; }
Usage method:
$str = '看看截取到哪里?'; echo cut($str,1); echo '<br>'; echo cut($str,4); echo '<br>'; echo cut($str,5); echo '<br>'; echo cut($str,5,false); echo '<br>'; $str = '中英文混合看看hello?'; echo cut($str,18); echo '<br>'; echo cut($str,50);
Output:
看... 看看... 看看... 看看 中英文混合看看hel... 中英文混合看看hello?
Explanation: Generally, UTF-8 format is 3 bytes, while GBK compatible gb2312 is generally 2 bytes, above Take UTF-8 encoding as an example.
The ellipsis mode can be switched on and off through the third parameter $more. The default value is true for with ellipses, and false for no ellipses.