PHP统计中文字符串个数,统计文章中文字数2020-06-10 10:22:49
本函数计算字符串中的中文字数,经常用在统计文章中的中文字数有多少private function str_utf8_chinese_word_count($str = "") {
$str = preg_replace(UTF8_SYMBOL_PATTERN, "", $str);
return preg_match_all(UTF8_CHINESE_PATTERN, $str, $arr);
}
/**统计中文字数
* @param str 要被统计的字符串
* @return 返回中文字数
* */
function countwordscn($str = "") {
define("UTF8_CHINESE_PATTERN", "/[\x{4e00}-\x{9fff}\x{f900}-\x{faff}]/u" );
define("UTF8_SYMBOL_PATTERN", "/[\x{ff00}-\x{ffef}\x{2000}-\x{206F}]/u" );
$str=preg_replace('/|()|()|()|()|()|()|()|()|()|()/isU','',$str);
$str=preg_replace('//is','',$str);
$str=preg_replace('/ /is'," ",$str);
$preg = "/]+>/i";
$replaceto = '';
$str = preg_replace($preg,'',$str);
$reg='/(\d+)|(\s{2,})|(,)|(\.)|(\")|(\()|(\))|(\[)|(\])/is';
$replaceto=' ';
$str=preg_replace($reg,$replaceto,$str);
$str = preg_replace('/\s(?=\s)/i', '', $str);
$str = preg_replace('/[\n\r\t]/i', ' ', $str);
$str = preg_replace(UTF8_SYMBOL_PATTERN, "", $str);
return $this -> str_utf8_chinese_word_count($str);
}
注意:该方法需要在PHP类中调用,使用示例:$num=$this->countwordscn($str);
变量$num就是返回的中文字数
Tags 标签字数统计PHP字数