判断提取一个字符串中英文字母和中文字符(二)

自己根据splitStr函数,写了一个可以根据指定长度截取字符串的函数,分享一下:
splitStrTitle($str,$part,$type = ‘cn’,$addSymbol = true)
函数功能:
$str为要截取的字符串,截取之后存入$string并返回.
$part为截取长度,如果$part<=0返回空串,如果$part>字串长度,直接返回原字串.
$type为截取方式,方式分为中文(双字节)cn截取和英文(单子节)en截取两种形式.如果为cn,将1个长度理解为2个字节.如果为en,将1个长度理解为1个字节.如字符串”一个例子”截取长度为3,cn模式下结果为”一个例”,en模式下为”一”.
$addSymbol为是否在截取的字符串后添加”..”.同样分为cn和en模式.如果为cn,将替换掉结果字符串最后两个字节.如果为en模式,考虑到英文书写习惯,将替换掉结果字符串最后一个单词,而不是最后两个字符.如果结果字符串只有一个单词,则同cn模式,只替换最后两个字节.

[coolcode lang=”php” download=”split.php”]
function splitStrTitle($str,$part,$type = ‘cn’,$addSymbol = true) {
$len = strlen ($str);
$step = $type == ‘cn’? 0.5 : 1;
$partEN = $type == ‘cn’? $part*2 : $part;
$i = 0;
$j = 0;
$hasCN = false;
$string =”;
if($partEN >= $len){
$string =$str;
}
else if($part > 0){
while ($j < $part && $i < $len ) { if (preg_match("/^[".chr(0xa1)."-".chr(0xff)."]+$/",$str[$i])) { if(($part - $j) > $step){
$string.=$str[$i].$str[$i+1];
$hasCN = true;
$i += 2;
}
$j += $step*2;
}
else {
$string.=$str[$i];
$j += $step;
$i += 1;
}

}
if($addSymbol && strlen ($string) > 2){
$string = $hasCN ? preg_replace(“/([“.chr(0xa1).”-“.chr(0xff).”]{2}$)|([“.chr(0xa1).”-“.chr(0xff).”]{2}[^”.chr(0xa1).”-“.chr(0xff).”]$)|([^”.chr(0xa1).”-“.chr(0xff).”]{2}$)/”,’..’,$string,1) : preg_replace_callback(“/(\W.$)|(^(\w+)(\w.?)$)|(\W\w+.$)/”,create_function(
‘$matches’,
‘if ($matches[3])
return “$matches[3]..”;
else return “..”;’

),$string,1);
}
}

return $string;

}
$str=”这是一个字符截取例子”;
$str = splitStrTitle($str,6,”cn”);
print_r($str);
[/coolcode]

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据