Question

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.

Was it helpful?

Solution 2

use array_diff

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

OTHER TIPS

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

$badwords = array('nous', 'lol', 'ene', 'seba'); 

$filtered_keywords=array_diff($keywords,$badwords);

Incorrect Array name most probably

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

it isnt $excluded_words, it is $badwords

You're missing a semicolon after

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

And you can use array_diff:

$filtered_keywords = array_diff($keywords, $badwords);

You missed the slashes / in the $badwords. and you missed the semicolon ; at the end of the fist 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);

?>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top