preg_match array items in string?

后端 未结 4 687
庸人自扰
庸人自扰 2020-12-10 21:44

Lets say I have an array of bad words:

$badwords = array(\"one\", \"two\", \"three\");

And random string:

$string = \"some          


        
4条回答
  •  情书的邮戳
    2020-12-10 22:31

    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

提交回复
热议问题