【问题标题】:PHP - Count how many times find a word from array listPHP - 计算从数组列表中找到一个单词的次数
【发布时间】:2014-08-22 14:20:06
【问题描述】:

首先我很抱歉标题不好,我的英语不够好,我的小问题并不简单(对我来说)。

无论如何,我有一个基本脚本,可以计算字符串中单词列表出现的次数。

$orto1 = substr_count($text," fingger ");
$orto2 = substr_count($text," apears ");
$orto3 = substr_count($text,"ghiven");

$ortog = $orto1 + $orto2 + $orto3;

现在,每当我要添加一个新单词时,我都感到很不舒服,所以,我想把所有单词放在一个数组中。

所以,我尝试使用 substr_count 以及在此处找到的几个示例,但均未成功。

我想设法创建类似的东西:

$array = array(" fingger ", " apears ", "ghiven", "suporting");
$total = substr_count($array, $mytext);
echo $total;

重要的是不区分大小写和“通配符”匹配。

有可能还是有其他最好的方法?

非常感谢! 里卡多

【问题讨论】:

    标签: php string search count


    【解决方案1】:

    我猜一个简单的循环就可以了?

    $total = 0
    $array = array(" fingger ", " apears ", "ghiven", "suporting");
    foreach($array as $word){
      $total += substr_count($word, $mytext);
    }
    echo $total;
    

    关于您可能使用的不区分大小写

    substr_count(strtoupper($word), strtoupper($mytext))
    

    【讨论】:

      【解决方案2】:

      天哪! 我没有想到像循环这样简单的方法:-)

      总之有一点小错误:

        $total += substr_count($word, $mytext);
      

      正确的做法是:

         $total += substr_count($mytext, $word);
      

      非常感谢!!!

      【讨论】:

        猜你喜欢
        • 2011-04-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-17
        • 2017-10-22
        • 1970-01-01
        相关资源
        最近更新 更多