当前位置:Gxlcms > PHP教程 > 4种PHP截取指定个数中文字符串的方法

4种PHP截取指定个数中文字符串的方法

时间:2021-07-01 10:21:17 帮助过:23人阅读

PHP网站制作中,有时候为了有更好的用户体验及布局我们经常会指定输出几个中文字符,以便有更好的视觉体验,也可以在用PHP截取UTF-8中文字符串中半个字符乱码问题。下面我分享两种PHP截取指定个数中文字符串的方法

一、通过UTF8编码字符的特性

UTF-8编码的字符可能由1~3个字节组成, 具体数目可以由第一个字节判断出来。(理论上可能更长,但这里假设不超过3个字节)第一个字节大于224的,它与它之后的2个字节一起组成一个UTF-8字符第一个字节大于192小于224的,它与它之后的1个字节组成一个UTF-8字符否则第一个字节本身就是一个英文字符(包括数字和一小部分标点符号)。


//$sourcestr 要处理的字符串 
//$cutlength 截取的长度(即字数)
function cut_str($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,
{
$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 && $ascnum<=90) //如果是大写字母,
{
$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 ($str_length>$cutlength){
$returnstr = $returnstr . "...";//超过长度时在尾处加上省略号
}
return $returnstr;


}
?>

二、通过字符的 ASCII 值特点1

function cutstr($string, $length) {
preg_match_all("/[\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]/", $string, $info);
for($i=0; $i $wordscut .= $info[0][$i];
$j = ord($info[0][$i]) > 127 ? $j + 2 : $j + 1;
if ($j > $length - 3) {
return $wordscut." ...";
}
}
return join('', $info[0]);
}
$string="242432PHP建站门户系统7890";
for($i=0;$i{
echo cutstr($string,$i)."
";
}
?>

三、通过字符的 ASCII 值特点2

function utf8_substr($str,$len)
{
for($i=0;$i<$len;$i++)
{
$temp_str=substr($str,0,1);
if(ord($temp_str) > 127)
{
$i++;
if($i<$len)
{
$new_str[]=substr($str,0,3);
$str=substr($str,3);
}
}
else
{
$new_str[]=substr($str,0,1);
$str=substr($str,1);
}
}
return join($new_str);
}
?>

四、通过字符的 ASCII 值特点3


function msubstr($str, $start, $len) {
$tmpstr = "";
$strlen = $start + $len;
for($i = 0; $i < $strlen; $i++) {
if(ord(substr($str, $i, 1)) > 0xa0) {
$tmpstr .= substr($str, $i, 2);
$i++;
} else
$tmpstr .= substr($str, $i, 1);
}
return $tmpstr;
}


?>

人气教程排行