0

想象一下,我有一个名为 uselessKeywords 的数组。它的值是“and”、“but”、“the”。

如果我还有一个带有“cool,and,but,and”的字符串,我怎么知道数组中的任何值在字符串中出现了多少次?

4

4 回答 4

3

类似的事情会做,但你必须注意误报,例如andoverand thesaurus

$uselesskeywords = array('and', 'but', 'the');
$regex = implode('|', $uselesskeywords);
$count = count(preg_grep("/($regex)/", "cool,and,but,and"));
于 2012-10-06T17:09:06.117 回答
0

您可以使用 foreach uselessKeywords 遍历字符串

$count = 0;
foreach($uselessKeywords as $needle){
    $count = $count + substr_count($str, $needle);
}

echo $count;
于 2012-10-06T17:13:53.980 回答
0

尝试这个..

<?php
function uselessKeywordOccurances ($myString, $theArray) {
    $occurances = array();
    $myTestWords = preg_split("/,/", $myString);
    for($i = 0; $i < count($myTestWords); $i++)     {
        $testWord = $myTestWords[$i];
        if (in_array($testWord, $theArray)) {
            array_push($occurances, $testWord);
        }
    }   
    $grouped = array_count_values($occurances);
    arsort($grouped);
    return $grouped;
}

$uselessKeywords = array("and", "but", "the");
$testWords = "cool,and,but,and,and,the,but,wonderful";
$result = uselessKeywordOccurances($testWords, $uselessKeywords);
var_dump($result);
?>

它应该返回出现的无用关键字,就像这样..

array(3) { ["and"]=> int(3) ["but"]=> int(2) ["the"]=> int(1) }
于 2012-10-06T18:18:59.743 回答
0

Marc B 的改进(添加一些昏迷以消除误报andoverthesaurus;我添加了前瞻,因为某些值可以一一对应):

$uselesskeywords = array('and', 'but', 'the');
$str = "cool,and,but,and";
$regex = implode('(?=,)|,', $uselesskeywords);
$count = count(preg_grep("/,$regex(?=,)/", ",$str,"));
于 2012-10-06T17:19:59.177 回答