想象一下,我有一個名爲uselessKeywords的數組。它具有「和」,「但」,「該」的值。如何判斷數組中的值是否在字符串中的次數
如果我還有一個帶有「cool,and,but,and」的字符串,我該如何判斷數組中的任何值在字符串中有多少次?
想象一下,我有一個名爲uselessKeywords的數組。它具有「和」,「但」,「該」的值。如何判斷數組中的值是否在字符串中的次數
如果我還有一個帶有「cool,and,but,and」的字符串,我該如何判斷數組中的任何值在字符串中有多少次?
沿着這條線會做些什麼,但你必須注意假陽性,如andover
和thesaurus
。
$uselesskeywords = array('and', 'but', 'the');
$regex = implode('|', $uselesskeywords);
$count = count(preg_grep("/($regex)/", "cool,and,but,and"));
你可以遍歷在foreach uselessKeywords
馬克·B(中$count = 0;
foreach($uselessKeywords as $needle){
$count = $count + substr_count($str, $needle);
}
echo $count;
改進字符串添加一些昏迷消除誤報andover
和thesaurus
;我已經添加了前瞻,因爲有一些數值就逐一):
$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) }
太棒了:) –
謝謝,這是偉大的:) –