引用地址:http://hi.baidu.com/%D4%C6%CB%AF%C1%CB/blog/item/84ee45eec325d7f2b2fb95a8.html
/** * 截取指定长度的字符串(UTF-8专用 汉字和大写字母长度算1,其它字符长度算0.5) * * @param string $string: 原字符串 * @param int $length: 截取长度 * @param string $etc: 省略字符(...) * @return string: 截取后的字符串 */ function cut_str_all($sourcestr, $cutlength = 80, $etc = '...') { $returnstr = ''; $i = 0; $n = 0.0; $str_length = strlen($sourcestr); //字符串的字节数 while ( ($n<$cutlength) and ($i<$str_length) ) { $temp_str = substr($sourcestr, $i, 1); $ascnum = ord($temp_str); //得到字符串中第$i位字符的ASCII码 if ( $ascnum >= 252) //如果ASCII位高与252 { $returnstr = $returnstr . substr($sourcestr, $i, 6); //根据UTF-8编码规范,将6个连续的字符计为单个字符 $i = $i + 6; //实际Byte计为6 $n++; //字串长度计1 } elseif ( $ascnum >= 248 ) //如果ASCII位高与248 { $returnstr = $returnstr . substr($sourcestr, $i, 5); //根据UTF-8编码规范,将5个连续的字符计为单个字符 $i = $i + 5; //实际Byte计为5 $n++; //字串长度计1 } elseif ( $ascnum >= 240 ) //如果ASCII位高与240 { $returnstr = $returnstr . substr($sourcestr, $i, 4); //根据UTF-8编码规范,将4个连续的字符计为单个字符 $i = $i + 4; //实际Byte计为4 $n++; //字串长度计1 } elseif ( $ascnum >= 224 ) //如果ASCII位高与224 { $returnstr = $returnstr . substr($sourcestr, $i, 3); //根据UTF-8编码规范,将3个连续的字符计为单个字符 $i = $i + 3 ; //实际Byte计为3 $n++; //字串长度计1 } elseif ( $ascnum >= 192 ) //如果ASCII位高与192 { $returnstr = $returnstr . substr($sourcestr, $i, 2); //根据UTF-8编码规范,将2个连续的字符计为单个字符 $i = $i + 2; //实际Byte计为2 $n++; //字串长度计1 } elseif ( $ascnum>=65 and $ascnum<=90 and $ascnum!=73) //如果是大写字母 I除外 { $returnstr = $returnstr . substr($sourcestr, $i, 1); $i = $i + 1; //实际的Byte数仍计1个 $n++; //但考虑整体美观,大写字母计成一个高位字符 } elseif ( !(array_search($ascnum, array(37, 38, 64, 109 ,119)) === FALSE) ) //%,&,@,m,w 字符按1个字符宽 { $returnstr = $returnstr . substr($sourcestr, $i, 1); $i = $i + 1; //实际的Byte数仍计1个 $n++; //但考虑整体美观,这些字条计成一个高位字符 } else //其他情况下,包括小写字母和半角标点符号 { $returnstr = $returnstr . substr($sourcestr, $i, 1); $i = $i + 1; //实际的Byte数计1个 $n = $n + 0.5; //其余的小写字母和半角标点等与半个高位字符宽... } } if ( $i < $str_length ) { $returnstr = $returnstr . $etc; //超过长度时在尾处加上省略号 } return $returnstr; }