Home > php教程 > php手册 > body text

php获取utf8字符串的字符长度实例

WBOY
Release: 2016-05-26 08:21:06
Original
1497 people have browsed it

今天没事来研究了一下在php中利用strlen计算字符串长度的一些实例了,但经过测试使用php自带的函数strlen在uft8与gbk编码时有很大的区别,下面我们一起来看看具体测试实例.

今晚在写框架的表单验证类时,需要判断某个字符串长度是否在指定区间内,很自然地,想到了PHP中的strlen函数,代码如下:

$str = 'Hello world!中'; 
echo strlen($str); // 输出12 
测试一下中文 
$str = '你好,世界!'; 
echo strlen($str); // GBK或GB2312下输出12,UTF-8下输出18
Copy after login

PHP内置的字符串长度函数strlen无法正确处理中文字符串,它得 到的只是字符串所占的字节数,对于GB2312的中文编码,strlen得到的值是汉字个数的2倍,而对于UTF-8编码的中文,就是3倍的差异了,在 UTF-8编码下,一个汉字占3个字节.

下面这个实例摘自大名鼎鼎的WordPress,非常精确的,另外需要注意的是本函数仅适用于utf-8 编码下的字符串,代码如下:

function utf8_strlen($string=null){ 
// 将字符串分解为单元 
preg_match_all("/./us", $string, $match); 
// 返回单元个数    
return count($match[0]); 
}
Copy after login

但以上代码在UTF-8编码下并不能处理GBK/GB2312的中文字符串,因为GBK/GB2312的中文字符会被识别为两个字符而计算出来的中文字符数量会翻倍,于是我想到了这么一个办法,代码如下:

$tmp = @iconv('gbk', 'utf-8', $str); 
if(!emptyempty($tmp)){ 
$str = $tmp; 
} 
preg_match_all('/./us', $str, $match); 
echo count($match[0]);
Copy after login

可兼容GBK/GB2312及UTF-8编码,经小量数据测试通过,但暂未确定是否完全正确.


文章网址:

随意转载^^但请附上教程地址。

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!