【问题标题】:PHP count words BETTER than str_word_countPHP 比 str_word_count 更好地计算单词
【发布时间】:2019-08-19 15:06:04
【问题描述】:

因为我读到 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 个。

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

【问题讨论】:

  • 好奇你在哪里读到str_word_count 有缺陷。
  • 我自己在较大的文本上测试过它,但它并没有像 Microsoft word 那样给我准确的字数。而且这里也提到了缺陷stackoverflow.com/questions/4786802/…

标签: php function count word-count


【解决方案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));

【讨论】:

  • 好的,谢谢!有什么办法让它把“不要”算作一个词而不是两个词?
  • 完美。是否有可能也排除数字? :) 字数用于翻译,以便人工翻译知道要翻译多少字。由于数字/数字不需要翻译,我不想把它们算作单词。
  • 对不起。我真的不明白。仅使用最后一行计算几乎所有字符。还是应该与上面的行结合使用?如果有,怎么做?
  • 对不起,我以某种方式删除了+
猜你喜欢
  • 2013-01-20
  • 2019-10-05
  • 1970-01-01
  • 1970-01-01
  • 2012-02-12
  • 2013-01-06
  • 1970-01-01
  • 2019-06-13
  • 2022-01-06
相关资源
最近更新 更多