uselessKeywords という配列があるとします。値は「and」、「but」、「the」です。
「cool,and,but,and」を含む文字列もある場合、配列の値が文字列に何回含まれているかをどのように知ることができますか?
これに沿った何かで十分ですが、 や などの誤検知に注意する必要がandover
ありthesaurus
ます。
$uselesskeywords = array('and', 'but', 'the');
$regex = implode('|', $uselesskeywords);
$count = count(preg_grep("/($regex)/", "cool,and,but,and"));
andover
Marc B の改善 (いくつかのカンマを追加して、誤検知を排除し、thesaurus
いくつかの値が 1 つずつになる可能性があるため、先読みを追加しました):
$uselesskeywords = array('and', 'but', 'the');
$str = "cool,and,but,and";
$regex = implode('(?=,)|,', $uselesskeywords);
$count = count(preg_grep("/,$regex(?=,)/", ",$str,"));
これを試して..
<?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) }
foreach uselessKeywords を使用して文字列をループできます
$count = 0;
foreach($uselessKeywords as $needle){
$count = $count + substr_count($str, $needle);
}
echo $count;