由于我读到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));