Compare elements of two arrays php -
so have 2 arrays:
$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');
i need compare elements of input phrases array bad words array , output new array phrases without bad words this:
$outputarray = array('nothing-bad-here', 'more-clean-stuff','one-more-clean', 'clean-clean');
i tried doing 2 foreach loops gives me opposite result, aka outputs phrases bad words. here code tried outputs opposite result:
function letscompare($inputphrases, $badwords) { foreach ($inputphrases $inputphrase) { foreach ($badwords $badword) { if (strpos(strtolower(str_replace('-', '', $inputphrase)), strtolower(str_replace('-', '', $badword))) !== false) { $result[] = ($inputphrase); } } } return $result; } $result = letscompare($inputphrases, $badwords); print_r($result);
this not clean solution, hope, you'll got going on. not hesitate ask clearence. 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);
Comments
Post a Comment