zoukankan      html  css  js  c++  java
  • php 计算字符串长度

    在项目的开发中,常常遇到要计算一个字符串的长度(中英文结合),由于产品要求不同,每个中文的长度要求也不一样。

    解决utf-8编码下的字符串长度(可自定义每个中英文算几个字节)

    /**
    * 计算字符串长度
    * @author Timothy
    * @param null $string 要计算的字符串,默认null
    * @param int $chinese 中文占几个字节,默认2
    * @param int $other 其他字符算几个字节,默认1
    * @return int 返回的长度
    */
    private function utf8_strlen($string = null, $chinese = 2, $other = 1) {
    // 将字符串分解为单元
    preg_match_all("/./us", $string, $match);
    $pattern = '/[^x00-x80]/';
    $count = 0;
    foreach ($match[0] as $key => $value) {
    $count = preg_match($pattern, $value) ? ($count + $chinese) : ($count + $other);
    }

    return $count;
    }
    注:
    1、preg_match_all("/./us", $string, $match);//"/./us",u表示默认为utf-8编码,s (PCRE_DOTALL)表示
    如果设定了此修正符,模式中的圆点元字符(.)匹配所有的字符,包括换行符。没有此设定的话,则不包括换行符。
    2、$pattern = '/[^x00-x80]/';//表示匹配中文
  • 相关阅读:
    poj3635(最短路)
    poj 3041( 最大匹配)
    poj 3522(生成树)
    poj 1904(强连通分量)
    poj 2446(二分匹配)
    poj 2400(最小权匹配)
    poj 2175(费用流消圈)
    poj 1256(搜索)
    poj 2195(最小费用流)
    poj 3613(最短路)
  • 原文地址:https://www.cnblogs.com/timothy-lai/p/5555524.html
Copyright © 2011-2022 走看看