4

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.

3
  • What is in $excluded_words? Commented Dec 26, 2012 at 7:35
  • $excluded_words should be $badwords? or i dint get it? Commented Dec 26, 2012 at 7:36
  • Corrected my example but code was ok. Sorry for that. Commented Dec 26, 2012 at 7:38

5 Answers 5

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

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

$filtered_keywords=array_diff($keywords,$badwords);
Sign up to request clarification or add additional context in comments.

Comments

2

use array_diff

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

Comments

1

Incorrect Array name most probably

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

it isnt $excluded_words, it is $badwords

Comments

1

You're missing a semicolon after

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

And you can use array_diff:

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

Comments

0

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);

?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.