Chinese string length is calculated mixing (a)

Mixing of Chinese contains string length is calculated, a Chinese, English, numbers are 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


Reproduced in: https: //my.oschina.net/zhouz/blog/213087

Guess you like

Origin blog.csdn.net/weixin_34248023/article/details/91728521