PHP 比 str_word_count 更好地计算单词
PHP count words BETTER than str_word_count
自从我读到 str_word_count 有缺陷后,我搜索了一个替代解决方案并遇到了以下问题,除了一个问题外,它总体上工作得很好。
function count_words($text) {
//it removes html tags
$text = preg_replace('/<[^>]*>/', '', $text);
//it removes html space code
$text = preg_replace(array('/ /'), ' ', $text);
//it removes multiple spaces with single
$text = trim(preg_replace('!\s+!', ' ', $text));
return count(explode(' ', $text));
}
问题是它将破折号“-”检测为单词。
示例:
This is a title - Additional Info
它将计算 7 个单词而不是 6 个。
是否可以从这个字数统计中排除单个字符,例如 -?
我只会数字数:
$count = preg_match_all("/[\w']+/", $text);
要获得删除 HTML 个标签和 HTML 个实体的功能:
$count = preg_match_all("/[\w']+/", html_entity_decode(strip_tags($text), ENT_QUOTES));
可能更好的方法是包含您认为组成单词的内容。添加 \w
未涵盖的任何内容。 i
使其不区分大小写:
$count = preg_match_all("/[a-z']+/i", html_entity_decode(strip_tags($text), ENT_QUOTES));
自从我读到 str_word_count 有缺陷后,我搜索了一个替代解决方案并遇到了以下问题,除了一个问题外,它总体上工作得很好。
function count_words($text) {
//it removes html tags
$text = preg_replace('/<[^>]*>/', '', $text);
//it removes html space code
$text = preg_replace(array('/ /'), ' ', $text);
//it removes multiple spaces with single
$text = trim(preg_replace('!\s+!', ' ', $text));
return count(explode(' ', $text));
}
问题是它将破折号“-”检测为单词。
示例:
This is a title - Additional Info
它将计算 7 个单词而不是 6 个。
是否可以从这个字数统计中排除单个字符,例如 -?
我只会数字数:
$count = preg_match_all("/[\w']+/", $text);
要获得删除 HTML 个标签和 HTML 个实体的功能:
$count = preg_match_all("/[\w']+/", html_entity_decode(strip_tags($text), ENT_QUOTES));
可能更好的方法是包含您认为组成单词的内容。添加 \w
未涵盖的任何内容。 i
使其不区分大小写:
$count = preg_match_all("/[a-z']+/i", html_entity_decode(strip_tags($text), ENT_QUOTES));