比较两个数组php的元素

时间:2017-04-14 12:02:40

标签: php arrays foreach strpos

所以我有两个数组:

$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 个答案:

答案 0 :(得分: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);
相关问题