計算中文混合字符串長度(一)
計算包含中文的混合字符串長度,一個中文、英文、數字 均為 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
最後更新:2017-04-03 12:54:58