想象一下,我有一个名为 uselessKeywords 的数组。它的值是“and”、“but”、“the”。
如果我还有一个带有“cool,and,but,and”的字符串,我怎么知道数组中的任何值在字符串中出现了多少次?
类似的事情会做,但你必须注意误报,例如andover
and thesaurus
。
$uselesskeywords = array('and', 'but', 'the');
$regex = implode('|', $uselesskeywords);
$count = count(preg_grep("/($regex)/", "cool,and,but,and"));
您可以使用 foreach uselessKeywords 遍历字符串
$count = 0;
foreach($uselessKeywords as $needle){
$count = $count + substr_count($str, $needle);
}
echo $count;
尝试这个..
<?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) }
Marc B 的改进(添加一些昏迷以消除误报andover
和thesaurus
;我添加了前瞻,因为某些值可以一一对应):
$uselesskeywords = array('and', 'but', 'the');
$str = "cool,and,but,and";
$regex = implode('(?=,)|,', $uselesskeywords);
$count = count(preg_grep("/,$regex(?=,)/", ",$str,"));