如何计算字符串php中的特定单词数组

时间:2016-06-23 13:04:15

标签: php

我需要计算字符串(How many times some word occurs in a string)中的一些特定单词,我怎样才能在php中执行此操作?

实施例

$words = array("woman", "murder", "rape", "female", "dowry");

$string = "A dowry deaths is a murder or suicide of a married woman caused by a dispute over her dowry.[4] In some cases, husbands and in-laws will attempt to extort a greater dowry through continuous harassment and torture which sometimes results in the wife committing suicide";

第一项是某个单词的捆绑,如果这个单词与下面的字符串匹配,则增加其值......

结果示例如:

dowry= 1;
murder =2;
women =5;

4 个答案:

答案 0 :(得分:2)

函数substr_count做你想做的事情

foreach($words as $word)
  echo $word .' ' . substr_count($string, $word) . "\n";

结果

women 0
murder 1
rape 0
female 0
dowry 3

demo

答案 1 :(得分:2)

尝试:

substr_count - 计算子字符串出现次数

$string = "A dowry deaths is a murder or suicide of a married woman caused by a dispute over her dowry.[4] In some cases, husbands and in-laws will attempt to extort a greater dowry through continuous harassment and torture which sometimes results in the wife committing suicide";

$words = array("women", "murder","rape","female","dowry");

foreach($words as $word) {
   echo $word." occurance are ".substr_count($string, $word)." times <br />";
}

输出:

女性出现 0

谋杀出现 1

强奸出现 0

女性出现 0

嫁妆出现 3

答案 2 :(得分:1)

您可以将字符串拆分为单词,然后遍历单词数组并检查它是否是$ words数组中的单词之一是相同的。

$arrayOfString = explode(" ", $string); //splitting in between spaces will return a new array
for ($i = 1; $i <= $arrayOfString.count(); $i++) //loop through the arrayOfString array
{
    for($j = $words.count(); $j >= 1; $j--)//loop through the words array
    {
         if($arrayOfString[i] == $words[j])
         {
              echo("You have a match with: " + $words[j]); //Add your count logic here
         }
    }
}

希望这适合你。

你可能有更好的方法来做这件事,但我自己也喜欢这种逻辑。

答案 3 :(得分:1)

使用substr_count将是直截了当的

$string = 'I just ate a delicious apple, and John ate instead a banana ice cream';
$words = ['banana', 'apple', 'kiwi'];
foreach($words as $word) {
    $hashmap[$word] = substr_count($string, $word);
}

现在$hashmap包含一个word => occurrences

的关联数组
array(3) {
  ["banana"] => int(1)
  ["apple"]  => int(1)
  ["kiwi"]   => int(0)
}    
相关问题