Restriction of words in comments

Asked

Viewed 1,552 times

10

I’m making a gallery of images that this gallery will have comments, comments are already being sent to the comic and returning as I wanted. But I need to make a filter for comments, in case they have some bad word the comment does not go up to the BD.

Example:

<textarea name="comentario">
"Caso o usuários escreva algum palavrão aqui, o mesmo não deve ser enviado"
</textarea>

Is there any PHP function that does this?

  • 1

    More interesting maybe you should think about creating a comment moderator, because sometimes even if the bad word itself does not appear in the sentence, it can still be offensive due to its context.

5 answers

7

You can use the function strpos, which returns the position of a given string within another. In your case, you can create an array with swear words and scroll through this array to see if it exists or not.

Example

<?php
    $frase = 'Caso o usuário fdp vsf escreva algum palavrão aqui, o mesmo não deve ser enviado';
    $palavrao = '';
    $palavroes  = array ('pqp', 'fdp','vsf');
     
    foreach ($palavroes as $value){
        $pos = strpos($frase, $value);
     
        if (!($pos === false))
            $palavrao = $palavrao.$value.'|';        
    }
     
    if (strlen($palavrao) > 1) {
           echo "Palavrões encontrados: ".$palavrao;
     } else {
           echo "Não tem palavrão";
       }
?>

See working on Ideone.

  • Comrade, your code is very good. But I saw a situation that might not work. If I put the word "bitch" in this array, it will identify a part of the word "dispute" as a swear word. I will try to increment something in the code to see how this small "problem can be solved".

  • 1

    @Dichrist, it really is a scenario that I didn’t think of. To avoid it, just insert the word with "spaces" at the beginning and end, theoretically would solve.

  • All right, buddy, I’m gonna test it. If I’m not mistaken, I actually made code that looks like yours, but I used the explode function in php to solve it. As far as I tested it was cool, but it goes that there is some scenario that I also have not thought hahaha. Anyway, your answer is great! + 1

5

Regular expression can also be another way out of this. I did something to detect sites with inappropriate urls not long ago, that way:

#blacklist.php
return array(
    '(.*)\.(xxx)',
    '4tube\.com',
    'clickme\.net',
    'cnnamador\.com',
    'extremefuse\.com',
    'fakku\.net',
    'fux\.com(?!\.br)', //Com .br é de advogados
    'heavy-r\.com', 
    'kaotic\.com', 
    'xhamster\.com',
    'porndoe\.com',
    'pornocarioca\.com',
    'rapebait\.net',
    'redtube\.com',
    'sex\.com',
    'vidmax\.com',
    'wipfilms\.net',
    'xvideos\.(com|net)',
    'porntube\.com',
);

That’s why I use a function:

public static function isBlockedHost($url)
{

    $keywords = (array) include 'blacklist.php';

    foreach ($keywords as $regex) {

        if (preg_match("/{$regex}/i", $url) > 0) return true;

    }

    return false;
}

Think that if I could do this with hosts, you can also do this with words you want to block. As they appear, you can add them to an array.

  • I prefer regular expression as well. But I am a layman in the subject. Up because I haven’t had the opportunity to use it yet.

5

It would be interesting besides having a lock serve-side have a lock cliente-side so that the user can make the appropriate corrections is to send the comment without any prohibited word.

If you value a readable text, doing this is indispensable, since deleting a word x may change the link of the comment.

Here is an example in js of the lock, basically it will only send to the php if you have no prohibited word. you can improve the return message to your user.

Example:

var list = ['noob', 'lammer'];

function blackList() {
  var texto = document.getElementById('texto');
  var tamTexto = texto.innerHTML.length;
  for (var i = 0; i < list.length; i++) {
    if (texto.innerHTML.indexOf(list[i]) >= 0) {
      return false;
    }
  }
  return true;
}

if (blackList()) {
  console.log("Comentario ok, envie para o php");
} else {
  console.log("Meça suas palavras parca!");
};
<p id="texto">Você é um noob, e seu primo um lammer</p>

2

You can also use a table in the database.

Create a table, for example:

Words

Columns

ID | Wrong Word | Right Word

Enter all the wrong words in the column Wrong Word and in the other column Right Word registers a word you want to replace the wrong one or just leave blank.

When registering the user message in the table make a while in this table using the str_replace in the text variable.

Pseudo-Code

TABELA = SELECT TABLE PALAVRAS

while TABELA
    $mensagem = STR_REPLACE (TABELA[PALAVRA_ERRADA], TABELA[PALAVRA_CERTA], $mensagem)

ECHO $mensagem

So he removes all inappropriate words.

2

In Codeigniter you have the text helper that has a function word_censor that removes or changes words from a text, you can only use this function in your application.

/**
 * Word Censoring Function
 *
 * Supply a string and an array of disallowed words and any
 * matched words will be converted to #### or to the replacement
 * word you've submitted.
 *
 * @access  public
 * @param   string  the text string
 * @param   string  the array of censoered words
 * @param   string  the optional replacement value
 * @return  string
 */
if ( ! function_exists('word_censor'))
{
    function word_censor($str, $censored, $replacement = '')
    {
        if ( ! is_array($censored))
        {
            return $str;
        }

        $str = ' '.$str.' ';

        // \w, \b and a few others do not match on a unicode character
        // set for performance reasons. As a result words like über
        // will not match on a word boundary. Instead, we'll assume that
        // a bad word will be bookeneded by any of these characters.
        $delim = '[-_\'\"`(){}<>\[\]|!?@#%&,.:;^~*+=\/ 0-9\n\r\t]';

        foreach ($censored as $badword)
        {
            if ($replacement != '')
            {
                $str = preg_replace("/({$delim})(".str_replace('\*', '\w*?', preg_quote($badword, '/')).")({$delim})/i", "\\1{$replacement}\\3", $str);
            }
            else
            {
                $str = preg_replace("/({$delim})(".str_replace('\*', '\w*?', preg_quote($badword, '/')).")({$delim})/ie", "'\\1'.str_repeat('#', strlen('\\2')).'\\3'", $str);
            }
        }

        return trim($str);
    }
}

example of use:

echo word_censor('Texto do comentario com um palavrao', array('palavrao'), '---');

example running on ideone

Browser other questions tagged

You are not signed in. Login or sign up in order to post.