preg_match array items in string?

后端 未结 4 648
庸人自扰
庸人自扰 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.

    0 讨论(0)
  • 2020-12-10 22:23

    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 { ... }
    
    0 讨论(0)
  • 2020-12-10 22:24

    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";
    }
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题