在项目的开发中,常常遇到要计算一个字符串的长度(中英文结合),由于产品要求不同,每个中文的长度要求也不一样。
解决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]/';//表示匹配中文