jscripter
jscripter

Reputation: 840

check substrings from array in string

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

Upvotes: 2

Views: 59

Answers (3)

jscripter
jscripter

Reputation: 840

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

Upvotes: 0

jscripter
jscripter

Reputation: 840

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

Upvotes: 0

xdazz
xdazz

Reputation: 160833

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)) {
  //..
}

Upvotes: 3

Related Questions