2017-04-14 149 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