封装的函数
代码语言:javascript复制//兼容中英文混排的字符串截取
function common_substr($sourcestr, $cutlength) {
$returnstr = '';
$i = 0;
$n = 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 >= 224) {//如果ascii位高与224,
if($n 3>$cutlength){
return $returnstr;
}
$returnstr = $returnstr . substr ( $sourcestr, $i, 3 ); //根据utf-8编码规范,将3个连续的字符计为单个字符
$i = $i 3; //实际byte计为3
$n =3;
//echo $n."n";
} elseif ($ascnum >= 192){ //如果ascii位高与192,
if( $n 2>$cutlength){
return $returnstr;
}
$returnstr = $returnstr . substr ( $sourcestr, $i, 2 ); //根据utf-8编码规范,将2个连续的字符计为单个字符
$i = $i 2; //实际byte计为2
$n =2;
} elseif ($ascnum >= 65 && $ascnum <= 90) {//如果是大写字母,
$returnstr = $returnstr . substr ( $sourcestr, $i, 1 );
$i = $i 1; //实际的byte数仍计1个
$n ; //但考虑整体美观,大写字母计成一个高位字符
}elseif ($ascnum >= 97 && $ascnum <= 122) {
$returnstr = $returnstr . substr ( $sourcestr, $i, 1 );
$i = $i 1; //实际的byte数仍计1个
$n ; //但考虑整体美观,大写字母计成一个高位字符
} else {//其他情况下,半角标点符号,
$returnstr = $returnstr . substr ( $sourcestr, $i, 1 );
$i = $i 1;
$n = $n 1;
}
}
return $returnstr;
}
经测试效果还行
未经允许不得转载:肥猫博客 » php字符串截取(兼容中英文混截)