Preg_replace with a template and an array object returning an empty array

I want an easy way to remove $ badwords elements 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 using str_ireplace , but it went wrong because it was being replaced inside strings in my array.

+4
source share
5 answers

use array_diff

 var_dump(array_diff($keywords, $badwords)); array(2) { [0]=> string(9) "sebastian" [2]=> string(6) "helene" } 
+2
source
 $keywords = array('sebastian','nous','helene','lol'); $badwords = array('nous', 'lol', 'ene', 'seba'); $filtered_keywords=array_diff($keywords,$badwords); 
+3
source

Invalid array name, most likely

 $filtered_keywords = array_filter(preg_replace($excluded_words,'',$keywords), 'strlen'); 

these are not $ excluded_words , these are $ badwords

+1
source

You are missing a semicolon after

 $keywords = array('sebastian','nous','helene','lol') 

And you can use array_diff :

 $filtered_keywords = array_diff($keywords, $badwords); 
+1
source

You missed the slashes / in $ badwords. and you missed the semicolon ; at the end of the first line. Try this code:

 <?php $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'); echo print_r($filtered_keywords); ?> 
0
source

All Articles