Check if the string contains any of the words

I need to check if a string contains any of the forbidden words. My requirements:

  • Case insensitive, so I used stripos()
  • The word should be separated by spaces, for example, if the forbidden word is “poker”, “playing poker” or “match with game poker”, should fall under the forbidden line, and “excellent training” should be under a good line.

I tried something like below

$string  = "poker park is great";

if (stripos($string, 'poker||casino') === false) 
{

echo "banned words found";
}
else

{
echo $string;
}
+4
source share
4 answers

You can use an array and join it

$arr = array('poker','casino','some','other', 'word', 'regex+++*much/escaping()');
$string = 'cool guy';

for($i = 0, $l = count($arr); $i < $l; $i++) {
    $arr[$i] = preg_quote($arr[$i], '/');   // Automagically escape regex tokens (think about quantifiers +*, [], () delimiters etc...)
}
//print_r($arr); // Check the results after escaping

if(preg_match('/\b(?:' . join('|', $arr). ')\b/i', $string)) { // now we don't need to fear 
    echo 'banned words found';
} else {
    echo $string;
}

It uses the word boundary and joins the array.

0
source

preg_match :

$string  = "poker park is great";

if (preg_match("/(poker|casino)/", $string)) {
  echo "banned words found";
} else {
  echo $string;
}

. , , , , i . , (, "" , , ), \b...
:

...
if (preg_match("/\b(poker|casino)\b/i", $string)) {
...
+6

MarcoS , , , . \b (\b - ) , .

$string  = "poker park is great";
if (preg_match("/\bpoker\b/", $string)) {
    echo "banned words found";
} else {
    echo $string;
}
+1
$string  = "park doing great with pokering. casino is too dangerous.";
$needles = array("poker","casino");
foreach($needles as $needle){
  if (preg_match("/\b".$needle."\b/", $string)) {
    echo "banned words found";
    die;
  }
}
echo $string;
die;
0

All Articles