zoukankan      html  css  js  c++  java
  • 计算中文混合字符串长度(一)

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


  • 相关阅读:
    (转)五大常用算法之二:动态规划算法
    (转)五大常用算法之一:分治算法
    dict
    usaco2
    usaco3
    usaco4
    usaco1
    并查集
    洛谷P1428小鱼比可爱
    洛谷P1967货车运输
  • 原文地址:https://www.cnblogs.com/zhouzme/p/5758518.html
Copyright © 2011-2022 走看看