-->

PHP Replacing swear words with phrases

2019-02-21 02:43发布

问题:

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.

For example:

bad word is 'dog'

user inputs -> 'You smell like a dog.'

instead of it replacing 'dog' with 'rainbow' or something, I want it to echo something like: 'You are a potty mouth'.

Here's what I have for code:

<?php

$find = array('dog', 'cat', 'bird');
$replace = 'You are a potty mouth.';

if (isset ($_POST['user_input'])&&!empty($_POST['user_input'])) {
    $user_input = $_POST['user_input']; 
    $user_input_new = str_ireplace($find, $replace, $user_input);

        echo $user_input_new;
}
?>

With this code it echos: 'You smell like a You are a pottymouth.'

I'm sure this is a repost and I apologize. Everything I've been able to find is documentation on how to replace only parts of strings, not entire ones.

回答1:

Well, in this case you can just check whether there is a "bad word" in the user input string, and if it returns true, echo "You are a potty mouth."

You would want to use strpos()

e.g.

if( strpos($_POST['user_input'],'dog')!==FALSE ) {
    echo('You are a potty mouth');
}

If you have an array of "bad words" you'll want to loop through them to check any occur within user input.



回答2:

I've been looking at the same issue recently, here's a script I was working on to filter certain words. Still a work in progress but it has the ability to output the user message or a custom message. Hope it helps or points you in the right direction.

define("MIN_SAFE_WORD_LIMIT", 3);
$safe = true;
$whiteList = array();
$blackList = array();

$text = 'Test words fRom a piece of text.';

$blCount = count($blackList);

for($i=0; $i<$blCount; $i++) {
    if((strlen($blackList[$i]) >= MIN_SAFE_WORD_LIMIT) && strstr(strtolower($text), strtolower($blackList[$i])) && !strstr(strtolower($text), strtolower($whiteList[$i]))) {
        $safe = false;
    }
}

if(!$safe) {
    // Unsafe, flag for action
    echo 'Unsafe';
} else {
    echo $text;
}


回答3:

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;
  }
}


回答4:

Heres an alternative solution, match words and replace with * len of str. this wont match words like Scunthorpe as it uses word boundaries, Also you you can add a 3rd param to reveal the first letters of the word so you know what word was said without seeing it.

<?php
$badwords = array('*c word', '*f word','badword','stackoverflow');

function swear_filter($str,$badwords,$reveal=null) {
    //Alternatively load from file
    //$words = join("|", array_filter(array_map('preg_quote',array_map('trim', file('badwords.txt')))));


    $words = join("|", array_filter(array_map('preg_quote',array_map('trim', $badwords))));
    if($reveal !=null && is_numeric($reveal)){
        return preg_replace("/\b($words)\b/uie", '"".substr("$1",0,'.$reveal.').str_repeat("*",strlen("$1")-'.$reveal.').""', $str);
    }else{
        return preg_replace("/\b($words)\b/uie", '"".str_repeat("*",strlen("$1")).""', $str);
    }

}


$str="There was a naughty Peacock from Scunthorpe and it said a badword, on stackoverflow";

//There was a naughty Peacock from Scunthorpe and it said a b******, on s************
echo swear_filter($str,$badwords,1);

//There was a naughty Peacock from Scunthorpe and it said a *******, on *************
echo swear_filter($str,$badwords);
?>