想象一下,我有一个名为uselessKeywords的数组。它的值为“and”,“but”,“the”。
如果我还有一个字符串,其中包含“cool,and,but,and”,如何判断数组中的任何值在字符串中的次数?
答案 0 :(得分:3)
这样做会有所作为,但您必须注意误报,例如andover
和thesaurus
。
$uselesskeywords = array('and', 'but', 'the');
$regex = implode('|', $uselesskeywords);
$count = count(preg_grep("/($regex)/", "cool,and,but,and"));
答案 1 :(得分:0)
你可以使用foreach uselessKeywords
遍历字符串$count = 0;
foreach($uselessKeywords as $needle){
$count = $count + substr_count($str, $needle);
}
echo $count;
答案 2 :(得分:0)
改进Marc B(添加一些逗号以消除误报andover
和thesaurus
;我添加了前瞻,因为某些值可以逐个显示):
$uselesskeywords = array('and', 'but', 'the');
$str = "cool,and,but,and";
$regex = implode('(?=,)|,', $uselesskeywords);
$count = count(preg_grep("/,$regex(?=,)/", ",$str,"));
答案 3 :(得分: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) }