PHP算出的单词比str_word_count

时间:2019-03-28 18:21:43

标签: php function count 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('/&nbsp;/'), ' ', $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个单词组成。

是否可以从字数中排除像-这样的单个字符?

1 个答案:

答案 0 :(得分:1)

我只想数几个字:

$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));