2012-10-06 75 views

回答

3

沿着這條線會做些什麼,但你必須注意假陽性,如andoverthesaurus

$uselesskeywords = array('and', 'but', 'the'); 
$regex = implode('|', $uselesskeywords); 
$count = count(preg_grep("/($regex)/", "cool,and,but,and")); 
+0

謝謝,這是偉大的:) –

0

你可以遍歷在foreach uselessKeywords

馬克·B(中
$count = 0; 
foreach($uselessKeywords as $needle){ 
    $count = $count + substr_count($str, $needle); 
} 

echo $count; 
0

改進字符串添加一些昏迷消除誤報andoverthesaurus;我已經添加了前瞻,因爲有一些數值就逐一):

$uselesskeywords = array('and', 'but', 'the'); 
$str = "cool,and,but,and"; 
$regex = implode('(?=,)|,', $uselesskeywords); 
$count = count(preg_grep("/,$regex(?=,)/", ",$str,")); 
+0

這是不重複改進 – Baba

+0

@Baba:我該怎麼辦?你不能評論所有的代碼。它會搞砸。 –

+0

如果你繼續以這種方式工作人員代碼,你會成爲一個投票磁鐵 – Baba

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) } 
+0

太棒了:) –

相關問題