James
James

Reputation: 11

Checking if any of the strings in an array matches a string

I'm trying to find out if a string matches any of my bad words in my array IE:

$badWords = Array('bad', 'words', 'go', 'here');
$strToCheck = "checking this string if any of the bad words appear";

if (strpos($strToCheck, $badWords)) { 
    // bad word found
}

the issue is strpos can only check for a string and not an array, is there a method of doing this without looping through the array of badwords?

Upvotes: 1

Views: 670

Answers (4)

Emil Vikström
Emil Vikström

Reputation: 91912

Not exactly, since all solutions inevitably must loop over your array, even if it's "behind the scenes". You can make a regular expression out of $badWords, but the runtime complexity will probably not be affected. Anyway, here's my regex suggestion:

$badWordsEscaped = array_map('preg_quote', $badWords);
$regex = '/'.implode('|', $badWordsEscaped).'/';
if(preg_match($regex, $strToCheck)) {
  //bad word found
}

Note that I've escaped the words to protect against regex-injections, if they contain any special regex characters such as / or .

Upvotes: 3

Ibrahim Azhar Armar
Ibrahim Azhar Armar

Reputation: 25745

Try This..

$badWords = array('hello','bad', 'words', 'go', 'here');
$strToCheck = 'i am string to check and see if i can find any bad words here';
//Convert String to an array
$strToCheck = explode(' ',$strToCheck);

foreach($badWords as $bad) {
    if(in_array($bad, $strToCheck)) {
        echo $bad.'<br/>';
    }
}

the above code will return all matched bad words, you can further extend it to implement your own logic like replacing the bad words etc.

Upvotes: 0

Mel
Mel

Reputation: 6157

in_array. Read question wrong.

Simplest implementation is to call strpos() for each of the badwords:

<?php
$ok = TRUE;
foreach($badwords AS $word)
{
    if( strpos($strToCheck, $word) )
    {
        $ok = FALSE;
        break;
    }
}
?>

Upvotes: 0

BenMorel
BenMorel

Reputation: 36484

array_intersect() gives you the list of matching words:

if (count(array_intersect(preg_split('/\s+/', $strToCheck), $badWords))) {
    // ...
}

Upvotes: 2

Related Questions