Home > php教程 > php手册 > strlen与mb_strlen字符串长度函数

strlen与mb_strlen字符串长度函数

WBOY
Release: 2016-06-21 08:57:14
Original
1323 people have browsed it

懂PHP的都知道strlen与mb_strlen是求字符串长度的函数,但是对于一些初学者来说,如果不看手册,也许不太清楚其中的区别。

懂PHP的都知道strlen与mb_strlen是求字符串长度的函数,但是对于一些初学者来说,如果不看手册,也许不太清楚其中的区别。
先看这样一段代码吧(先决条件是:字符编码为UTF-8):


$str = '懂PHP的都知道strlen与mb_strlen是求字符串长度的函数';
echo strlen($str)'.
'.mb_strlen($str,'utf-8');
?>

运行上述代码,返回值如下:
66
34

怎么样?strlen中,中文是三个字节的长度,英文则是一个字节的长度!mb_strlen中,都被计算为一字节的长度!所以,我们有时候用substr来截取UTF-8中文字符串的时候,经常会出现乱码,就是这个原因了!
下面提供一个截取UTF-8字符串的函数:

function cutstr($sourcestr,$cutlength){
$returnstr = '';
$i = 0;
$n = 0;
$str_length = strlen($sourcestr);
$mb_str_length = mb_strlen($sourcestr,'utf-8');
while(($n $temp_str = substr($sourcestr,$i,1);
$ascnum = ord($temp_str);
if($ascnum >= 224){
$returnstr = $returnstr.substr($sourcestr,$i,3);
$i = $i + 3;
$n++;
}
elseif($ascnum >= 192){
$returnstr = $returnstr.substr($sourcestr,$i,2);
$i = $i + 2;
$n++;
}
elseif(($ascnum >= 65) && ($ascnum $returnstr = $returnstr.substr($sourcestr,$i,1);
$i = $i + 1;
$n++;
}
else{
$returnstr = $returnstr.substr($sourcestr,$i,1);
$i = $i + 1;
$n = $n + 0.5;
}
}
if ($mb_str_length > $cutlength){
$returnstr = $returnstr . "...";
}
return $returnstr;
}

使用例子:


$str = '有效期最长三个月,超过有效期系统将自动删除本条信息';
//echo strlen($str);
//echo '


'.mb_strlen($str,'utf-8');
echo '
'.$str;
echo '
'.cutstr($str,24);
?>
 



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template