2017-04-14 148 views
0

所以,我有兩個數組:比較的兩個數組PHP元素

$badwords = array('bad-word', 'some-racist-term', 'nasty', 'bad-language'); 

$inputphrases = array('this-is-sentence-with-bad-word', 'nothing-bad-here', 'more-clean-stuff', 'this-is-nasty', 'this-contains-some-racist-term', 'one-more-clean', 'clean-clean', 'contains-bad-language'); 

我需要比較不好的話陣列和輸出新的數組與短語無不良的話這樣的輸入短語數組的元素:

$outputarray = array('nothing-bad-here', 'more-clean-stuff','one-more-clean', 'clean-clean'); 

我試着用兩個foreach循環做這件事,但它給了我相反的結果,也就是說它輸出帶有不良詞的短語。 這裏是代碼我試過輸出相反的結果:

function letsCompare($inputphrases, $badwords) 
{ 
    foreach ($inputphrases as $inputphrase) { 

     foreach ($badwords as $badword) { 

      if (strpos(strtolower(str_replace('-', '', $inputphrase)), strtolower(str_replace('-', '', $badword))) !== false) { 
       $result[] = ($inputphrase); 

      } 
     } 
    } 
return $result; 
} 

$result = letsCompare($inputphrases, $badwords); 
print_r($result); 

回答

1

這不是一個乾淨的解決方案,但是希望你會擁有和正在發生的事情。不要猶豫,要求清理。 repl.it link

$inputphrases = array('this-is-sentence-with-bad-word', 'nothing-bad-here', 'more-clean-stuff', 'this-is-nasty', 'this-contains-some-racist-term', 'one-more-clean', 'clean-clean', 'contains-bad-language'); 


$new_arr = array_filter($inputphrases, function($phrase) { 
    $badwords = array('bad-word', 'some-racist-term', 'nasty', 'bad-language'); 
    $c = count($badwords); 
    for($i=0; $i<$c; $i++) { 
    if(strpos($phrase, $badwords[$i]) !== false){ 
     return false; 
    } 
    } 
    return true; 
}); 

print_r($new_arr); 
+0

起初它看起來像它的工作正常,但由於某種原因,它只是也沒有與大量的查詢工作。例如添加壞詞john-day-yahweh和輸入詞組john-day-yahweh-bro,它將不起作用。請看這裏: https://repl.it/HJbW/2 P.S.我需要strtolower和str_replace,因爲數組中的一些短語是大寫的,有些短劃線,有些沒有。感謝您的幫助 – DadaB

+0

這是一個經典的0,錯誤的混淆的PHP - ))更新的答案,也修復repl.it片段https://repl.it/HJbW/3 – marmeladze

+0

作品像一個魅力。非常感謝您的幫助! – DadaB