【问题标题】:substr_count() count whole words in php [duplicate]substr_count()计算php中的整个单词[重复]
【发布时间】:2017-03-01 07:28:19
【问题描述】:

我是 php 的新手,所以,我正在制作一个单词计数器程序。我试图计算网站中有多少特定单词的实例。 所以,我使用 Substr_count 来计算单词,但问题是它把像“sunlight”这样的单词当作包含像“sun”这样的单词。

这是我的代码。

 /*When the user types the word*/
 $search = $_POST["texto"]; 

 /*The website*/
 $page = $_POST["Web"];

 $web = file_get_contents($page);

 /*Count words*/
 $result = (substr_count(strip_tags(strtolower($web)), strtolower($search)));

/*Display the information*/
if($result == 0){
echo "the word " .mb_strtoupper($search). " doesn't appear";    
}else{
echo "the word " .mb_strtoupper($search). " appears $result times";
}

有什么办法可以解决这个问题吗?我尝试了 str_word_count 和 preg_match_all 但这显示的数字很大。

【问题讨论】:

  • 计算机如何知道它只需要选择太阳而不是太阳光?你能在问题中添加一些示例数据吗
  • @Wolvy substr - 完全代表sub - 较小、较小(部分)和string...它没有考虑“单词”是什么
  • @Wolvy - 你应该考虑改用正则表达式
  • @Wolvy,使用正则表达式。检查这个话题stackoverflow.com/questions/9348326/…

标签: php search word


【解决方案1】:

这样就可以了:

/*Count words*/
$result = preg_match_all('/\b'. strtolower($search) .'\b/', strtolower($web));

【讨论】:

  • 谢谢,您的解决方案有效
  • 没问题的狼
【解决方案2】:

我会使用str_word_count() 的组合来获取所有单词,并使用array_count_values() 来计算这些单词出现的次数:

# Get an array with lowercase words
$array_with_words = str_word_count(strtolower('string to analyze'), 1);

# Get a count of all unique values
$array_with_words_count = array_count_values($array_with_words);

# Get the count of the word you are looking for
$your_count = $array_with_words_count[ strtolower('your_word') ];

【讨论】:

    【解决方案3】:

    str_word_cound($expression, 1) 函数将为您提供一个包含单词的关联数组,然后您可以使用 foreach 循环一次并构造一个具有单词频率的数组,如下所示:

    $expr = "My test expression. <b>My</b> world.";
    $words = str_word_count(strip_tags(strtolower($expr)), 1);
    $groupedWords = [];
    foreach ($words as $word) {
        print_r($word);
        $groupedWords[$word] ++;
    }
    print_r($groupedWords);
    

    将打印:

    Array
    (
        [my] => 2
        [test] => 1
        [expression] => 1
        [world] => 1
    )
    

    查看一个词被使用了多少次:

    var_dump(array_key_exists('specific_word_you_look_for', $groupedWords) ? $groupedWords['specific_word_you_look_for'] : false); 
    
    // will output the frequency or false if not found
    

    【讨论】:

      【解决方案4】:

      如果您想使用预定义函数,请使用 str_word_count()
      示例:

      <?php
      echo str_word_count("stack gives answer");
      ?>
      

      输出:3

      【讨论】:

      • 计算单词的总数,而不是特定单词在字符串中出现的次数。
      猜你喜欢
      • 2023-04-11
      • 2017-10-22
      • 2013-12-06
      • 2011-04-25
      • 1970-01-01
      • 2020-01-16
      • 2013-12-09
      • 2019-10-16
      • 2013-09-21
      相关资源
      最近更新 更多