$zhStr = '您好,中国!'; $str = 'Hello,中国!'; // 计算中文字符串长度 function utf8_strlen($string = null) { // 将字符串分解为单元 preg_match_all("/./us", $string, $match); // 返回单元个数 return count($match[0]); } echo utf8_strlen($zhStr); // 输出:6 echo utf8_strlen($str); // 输出:9
上述是WordPress中的一段代码,主要思想就是先用正则将字符串分解为个体单元,然后再计算单元的个数即字符串的长度
注:只能处理utf-8编码下的字符串
转载于:https://blog.51cto.com/windchaser/1254295