计算中文混合字符串长度(一)

计算中文混合字符串长度
本文介绍了一种在PHP中计算包含中文字符的混合字符串长度的方法,通过正则表达式匹配和函数实现,适用于UTF-8编码,对于理解和处理多语言字符串有实际应用价值。

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


转载于:https://my.oschina.net/zhouz/blog/213087

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值