计算包含中文的混合字符串长度,一个中文、英文、数字 均为 1
function resolveContainCn($string, $charset = 'utf-8')
{
if ($string == '') {
return '';
}
if ($charset == 'utf-8') {
$pa = "/[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]/";
}
else {
$pa = "/[x01-x7f]|[xa1-xff][xa1-xff]/";
}
$matches = array();
preg_match_all($pa, $string, $matches);
return $matches[0];
}
function strlenCn($string, $charset = 'utf-8')
{
if (function_exists('mb_strlen')) {
return mb_strlen($string, $charset);
}
return count(resolveContainCn($string, $charset));
}
$str = 'abcd计算字符串长度12345';
echo $str;
echo '<br>';
echo strlenCn($str); // 16