计算包含中文的混合字符串长度,一个中文、英文、数字 均为 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


相关文章:

  • 2022-12-23
  • 2021-12-08
  • 2021-09-27
  • 2021-09-30
  • 2022-12-23
  • 2021-06-24
猜你喜欢
  • 2022-01-05
  • 2022-01-05
  • 2022-12-23
  • 2022-12-23
  • 2021-07-01
  • 2021-12-27
  • 2022-12-23
相关资源
相似解决方案