Search code examples
phppreg-replacestr-replacearray-difference

preg_replace with pattern and subject array returning empty array


I want a simple way to delete elements of $badwords from $keywords.

What I have (as an example)

$keywords = array('sebastian','nous','helene','lol'); //it could be anything in fact
$badwords = array('nous', 'lol', 'ene', 'seba'); //array full of stop words that I won't write here
$filtered_keywords = array_filter(preg_replace($badwords,'',$keywords), 'strlen');
print_r($filtered_keywords);

What I expected

Array ( [0] => samaha [1] => helene ) 

What I got

 Sweet nothing :)

I tried to use str_ireplace but it went bad because it was replacing within the strings in my array.


Solution

  • use array_diff

    var_dump(array_diff($keywords, $badwords));
    array(2) {
      [0]=>
      string(9) "sebastian"
      [2]=>
      string(6) "helene"
    }