2

I want to exclude some result if it contains a word of an list of words(array)

For example:

$result = 'http://www.facebook.com/plugins/likebox.php';
$discardKeys = array('chat', 'facebook', 'twitter');

Like this way:

if (strpos($result,$discardKeys)==false) {
    echo $result;
}

3 Answers 3

3

You could use a regex:

$result = 'http://www.facebook.com/plugins/likebox.php';
$discardKeys = array('chat', 'facebook', 'twitter');
$discardKeys = array_map('preg_quote', $discardKeys);

if (preg_match('/'.implode('|', $discardKeys).'/', $result, $matches)) {
  //..
}
Sign up to request clarification or add additional context in comments.

1 Comment

+1 for actually remembering to preg_quote, but you should use () for regex delimiters - otherwise you'd need to escape slashes which makes the whole preg_quote function much less tidy (you'd need to pass an extra argument)
0

By the way I post this another but longer solution:

function istheRight($url, $discardKeys){
    foreach ($discardKeys as $key) {
        if (strpos($url, $key) == true) {return false;}
    }
    return true;
}

So in the example:

$result = 'http://www.facebook.com/plugins/likebox.php';
$discardKeys = array('chat', 'facebook', 'twitter');

if (isTheRight($result, $discardKeys)) {echo $result;}

Comments

0

And here is this shorter answer using str_replace to check is $result changes :

$result = 'http://www.facebook.com/plugins/likebox.php';
$discardKeys = array('chat', 'facebook', 'twitter');

if ($result == str_replace($discardKeys, "", $result)) {echo $result;}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.