我们经常会遇到需要截取字符串(含中文汉字)长度的情况,比如标题显示不能超过多少字符,超出的长度用…表示,以下函数可以满足你的需求。
1 /* 2 3 Utf-8、gb2312都支持的汉字截取函数 4 5 cut_str(字符串, 截取长度, 开始长度, 编码); 6 7 编码默认为 utf-8 8 9 开始长度默认为 0 10 11 */ 12 13 function cutStr( $string , $sublen , $start = 0, $code = 'UTF-8' ){ 14 15 if ( $code == 'UTF-8' ){ 16 17 $pa = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xef][\x80-\xbf][\x80-\xbf]|\xf0[\x90-\xbf][\x80-\xbf][\x80-\xbf]|[\xf1-\xf7][\x80-\xbf][\x80-\xbf][\x80-\xbf]/" ; 18 19 preg_match_all ( $pa , $string , $t_string ); 20 21 22 23 if ( count ( $t_string [0]) - $start > $sublen ) return join ('', array_slice 24 ( $t_string [0], $start , $sublen ))."..." ; 25 26 return join ('', array_slice ( $t_string [0], $start , $sublen )); 27 28 } else { 29 30 $start = $start *2 ; 31 32 $sublen = $sublen *2 ; 33 34 $strlen = strlen ( $string ); 35 36 $tmpstr = '' ; 37 38 39 40 for ( $i =0; $i < $strlen ; $i ++ ){ 41 42 if ( $i >= $start && $i <( $start + $sublen )){ 43 44 if ( ord ( substr ( $string , $i , 1))>129 ){ 45 46 $tmpstr .= substr ( $string , $i , 2 ); 47 48 } else { 49 50 $tmpstr .= substr ( $string , $i , 1 ); 51 52 } 53 54 } 55 56 if ( ord ( substr ( $string , $i , 1))>129) $i ++ ; 57 58 } 59 60 if ( strlen ( $tmpstr )< $strlen ) $tmpstr .= "..." ; 61 62 return $tmpstr ; 63 64 } 65 66 } 67 68 // 使用方法如下 69 70 $str = "jQuery插件实现的加载图片和页面效果" ; 71 72 echo cutStr( $str ,16);