0

uselessKeywords という配列があるとします。値は「and」、「but」、「the」です。

「cool,and,but,and」を含む文字列もある場合、配列の値が文字列に何回含まれているかをどのように知ることができますか?

4

4 に答える 4

3

これに沿った何かで十分ですが、 や などの誤検知に注意する必要がandoverあり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

andoverMarc B の改善 (いくつかのカンマを追加して、誤検知を排除し、thesaurusいくつかの値が 1 つずつになる可能性があるため、先読みを追加しました):

$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 に答える
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);
?>

次のように、uselessKeywords の出現を返す必要があります。

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

foreach uselessKeywords を使用して文字列をループできます

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

echo $count;
于 2012-10-06T17:13:53.980 に答える