preg_match array items in string?

后端 未结 4 689
庸人自扰
庸人自扰 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:21

    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.

提交回复
热议问题