PHP Replacing swear words with phrases

前端 未结 4 1128
旧时难觅i
旧时难觅i 2021-01-17 02:18

So I get how to replace certain words with other ones. What I\'m trying to figure out is how to take a word and replace it with a phrase and eliminate all other input.

4条回答
  •  甜味超标
    2021-01-17 03:12

    You don't want to replace the bad words, but the whole string, so you should just match and if matched set the whole string to your replacement string.

    Also, as pointed out in the comments the words can be part of another, valid, word so if you want to take that into account, you should match only whole words.

    This simple example uses word boundaries in a regular expression to match your words (in the example this would be in a loop, looping over your bad words array):

    foreach ($find as $your_word)
    {
      $search = '/\b' . preg_quote($your_word) . '\b/i';
      if (preg_match($search, $_POST['user_input']) === 1)
      {
        // a match is found, echo or set it to a variable, whatever you need
        echo $replace;
        // break out of the loop
        break;
      }
    }
    

提交回复
热议问题