中文字符串截取的方法
在开发的过程中经常会用到字符串截图,
尤其是中文很是头疼,给大家提供一个中文的截取方法。
//字符截断,中文算2个字符 function newstr($string, $length, $dot="...") { if(strlen($string) <= $length) {return $string;} $string = str_replace(array('&', '"', '<', '>'), array('&','"','<','>'), $string); $strcut = '';$n = $tn = $noc = $noct = $nc = $tnc =0; while($n < strlen($string)) { $t = ord($string[$n]); if($t == 9 || $t == 10 || (32 <= $t && $t <= 126)) { $tn = 1; $n++; $noct++; } elseif(194 <= $t && $t <= 223) { $tn = 2; $n += 2; $noct += 2; } elseif(224 <= $t && $t <= 239) { $tn = 3; $n += 3; $noct += 2; } elseif(240 <= $t && $t <= 247) { $tn = 4; $n += 4; $noct += 2; } elseif(248 <= $t && $t <= 251) { $tn = 5; $n += 5; $noct += 2; } elseif($t == 252 || $t == 253) { $tn = 6; $n += 6; $noct += 2; } else {$n++;} if($noct >= $length){if($noct==0)$noc=$noct;if($nc==0)$nc=$n;if($tnc==0)$tnc=$tn;} } if($noct<=$length){return str_replace(array('&','"','<','>'), array('&', '"', '<', '>'), $string);} if($noc > $length) {$nc -= $tnc;} $strcut = substr($string, 0, $nc); $strcut = str_replace(array('&','"','<','>'), array('&', '"', '<', '>'), $strcut); return $strcut.$dot; }
好不好用可以试试,我觉得还不错。
发布时间:2018-04-26,10:46:01
中文字符串截取,php代码实现。