PHP计数的字比str_word_count好

问题描述 投票:0回答:1

由于我读到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个单词。

是否有可能从这个字数中排除单个字符?

php function count word-count
1个回答
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));
© www.soinside.com 2019 - 2024. All rights reserved.