高效的固定长度字符串的截取函数
高效的固定长度字符串的截取函数--只要一次截取和一次正则替换就可以办到: & h$ d0 x2 w! | I9 D; a
( b/ _; X: r0 T, g5 B
<? 8 c$ i6 t: E8 S+ t8 N$ {0 |4 [
# U% Q" p# ^* Z2 sfunction toFixLen($str,$len){ //固定长度字符串的截取8 H" H8 [/ q# c8 ]
if($len>=strlen($str)||!$len) return $str; ( {: [" Z* B. J4 L
8 d: x' y, I! b, M) l8 G* s6 ^3 P
$len-=3; - _+ d1 S- ^( g# {# l
$tempstr1 = substr($str,0,$len); //截取字符串 4 r; a# Y5 p7 `* ^/ z
$tempstr2 = preg_replace('/([x81-xff]+)$/ms','',$tempstr1,1); //去掉结尾的连续汉字字符 4 N& e9 M; c6 X0 h$ G
if(!is_int((strlen($tempstr1)-strlen($tempstr2))/2)){ //去掉的字符为奇数? . Z/ r: r% u0 j" L0 k4 Q/ ^
$tempstr1 = substr($str,0,$len-1); " I9 _( t6 A( L& y3 n
}
! p$ {1 U5 W6 U$ h4 [1 w6 ?: F3 ~ return $tempstr1."..."; $ M+ r( y! w. c7 W4 r" J# C
} * e7 n) D" N# ~' Q+ v& ~4 V
/ c6 a( ?( ?9 M, M i- z?>