php字符串截取经常用到,此函数将中英文按照1比3截取,如果按照1比2截取将$noc += 3;改成$noc += 2;
从网上找的一个处理函数
- function _str_cut($sourcestr,$cutlength,$suffix='...') {
- $str_length = strlen($sourcestr);
- if($str_length <= $cutlength) {
- return $sourcestr;
- }
- $returnstr='';
- $n = $i = $noc = 0;
- while($n < $str_length) {
- $t = ord($sourcestr[$n]);
- if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) {
- $i = 1;
- $n++;
- $noc++;
- } elseif(194 <= $t && $t <= 223) {
- $i = 2;
- $n += 2;
- $noc += 3;
- } elseif(224 <= $t && $t <= 239) {
- $i = 3;
- $n += 3;
- $noc += 3;
- } elseif(240 <= $t && $t <= 247) {
- $i = 4;
- $n += 4;
- $noc += 3;
- } elseif(248 <= $t && $t <= 251) {
- $i = 5;
- $n += 5;
- $noc += 3;
- } elseif($t == 252 || $t == 253) {
- $i = 6;
- $n += 6;
- $noc += 3;
- } else {
- $n++;
- }
- if($noc >= $cutlength) {
- break;
- }
- }
- if($noc > $cutlength) {
- $n -= $i;
- }
- $returnstr = substr($sourcestr, 0, $n);
- if ( substr($sourcestr, $n, 6)){
- $returnstr = $returnstr . $suffix;//超过长度时在尾处加上省略号
- }
- return $returnstr;
- }
转载于:https://blog.51cto.com/zhixinhu/1071111