php计算utf8字符串长度

时间:2023-03-10 00:45:57
php计算utf8字符串长度

  strlen()函数计算中文字符不太友好。扩展的mb_strlen()函数可以补充这个。如果没有这个扩展,也可以利用正则匹配分解。

  函数如下:

// 对utf-8字符的长度
function utf8len($string) {
if (function_exists('mb_strlen')){
return mb_strlen($string, 'utf-8');
}
// 将字符串分解为单元
preg_match_all("/./us", $string, $match); // 返回单元个数
return count($match[0]);
} $str = '测试。字符串1a'; echo utf8len($str);//