preg_match array items in string?

我怕爱的太早我们不能终老 提交于 2019-11-28 13:05:53

How about this:

$badWords = array('one', 'two', 'three');
$stringToCheck = 'some stringy thing';
// $stringToCheck = 'one stringy thing';

$noBadWordsFound = true;
foreach ($badWords as $badWord) {
  if (preg_match("/\b$badWord\b/", $stringToCheck)) {
    $noBadWordsFound = false;
    break;
  }
}
if ($noBadWordsFound) { ... } else { ... }

Why do you want to use preg_match() here?
What about this:

foreach($badwords as $badword)
{
  if (strpos($string, $badword) !== false)
    echo "sorry bad word found";
  else
    echo "string contains no bad words";
}

If you need preg_match() for some reasons, you can generate regex pattern dynamically. Something like this:

$pattern = '/(' . implode('|', $badwords) . ')/'; // $pattern = /(one|two|three)/
$result = preg_match($pattern, $string);

HTH

If you want to check each word by exploding the string into words, you can use this:

$badwordsfound = count(array_filter(
    explode(" ",$string),
    function ($element) use ($badwords) {
        if(in_array($element,$badwords)) 
            return true; 
        }
    })) > 0;

if($badwordsfound){
   echo "Bad words found";
}else{
   echo "String clean";
}

Now, something better came to my mind, how about replacing all the bad words from the array and check if the string stays the same?

$badwords_replace = array_fill(0,count($badwords),"");
$string_clean = str_replace($badwords,$badwords_replace,$string);
if($string_clean == $string) {
    echo "no bad words found";
}else{
    echo "bad words found";
}

Here is the bad word filter I use and it works great:

private static $bad_name = array("word1", "word2", "word3");

// This will check for exact words only. so "ass" will be found and flagged 
// but not "classic"

$badFound = preg_match("/\b(" . implode(self::$bad_name,"|") . ")\b/i", $name_in);

Then I have another variable with select strings to match:

// This will match "ass" as well as "classic" and flag it

private static $forbidden_name = array("word1", "word2", "word3");

$forbiddenFound = preg_match("/(" . implode(self::$forbidden_name,"|") . ")/i", $name_in);

Then I run an if on it:

if ($badFound) {
   return FALSE;
} elseif ($forbiddenFound) {
   return FALSE;
} else {
   return TRUE;
}

Hope this helps. Ask if you need me to clarify anything.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!