Determine if a string contains one of a set of words in an array

I need a simple word filter that will kill the script if it detects a filtered word in a string.

say my words below

$showstopper = array(badword1, badword2, badword3, badword4);

$yourmouth = "im gonna badword3 you up";

if(something($yourmouth, $showstopper)){ 
//stop the show
}
+2
source share
5 answers

You can blast an array of icons into a regular expression and see if it matches the hay side. Or you can just iterate over the array and check each word separately.

From the comments:

$re = "/(" . implode("|", $showstopper) . ")/"; //  '/(badword1|badword2)/'
if (preg_match($re, $yourmouth) > 0) { die("foulmouth"); }
+6
source

in_array () is your friend

    $yourmouth_array = explode(' ',$yourmouth);
    foreach($yourmouth_array as $key=>$w){
       if (in_array($w,$showstopper){
         // stop the show, like, replace that element with '***'
         $yourmouth_array[$key]= '***';
       }
    }
$yourmouth = implode(' ',$yourmouth_array);
+1
source

, foreach preg_match.

$showstopper = array('badword1', 'badword2', 'badword3', 'badword4');
$yourmouth = "im gonna badword3 you up";

$check = str_replace($showstopper, '****', $yourmouth, $count);
if($count > 0) { 
     //stop the show
}
+1

, . .

$showstopper = array('badword1' => 1, 'badword2' => 1, 'badword3' => 1, 'badword4' => 1);
$yourmouth = "im gonna badword3 you up";

// split words on space
$words = explode(' ', $yourmouth);
foreach($words as $word) {
    // filter extraneous characters out of the word
    $word = preg_replace('/[^A-Za-z0-9]*/', '', $word);
    // check for bad word match
    if (isset($showstopper[$word])) {
        die('game over');
    }
}

preg_replace , , - bad_word3. , .

+1

not sure why you need it, but there is a way to check and get the bad words that were used

$showstopper = array(badword1, badword2, badword3, badword4);
$yourmouth = "im gonna badword3 you up badword1";

function badWordCheck( $var ) {

    global $yourmouth;
    if (strpos($yourmouth, $var)) {
        return true;
    }

}

print_r(array_filter($showstopper, 'badWordCheck'));

array_filter () returns an array of bad words, so if its counter () is 0, then nothing was said

0
source

All Articles