Restriction of words in comments

10

I'm doing a gallery of images that in this gallery will have comments, the comments are already being sent to the DB and returning the way I wanted. But I need to make a filter for the comments, if they have any bad words the comment does not rise to the DB.

Example:

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

Is there a PHP function that does this?

    
asked by anonymous 05.11.2015 / 12:41

5 answers

7

You can use the strpos function, which returns the string within another. In your case, you can create an array with bad words and go through this array by checking whether 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 at Ideone .

    
05.11.2015 / 12:51
5

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

#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',
);

This is how 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 that you want to block. As they pop up, you can add them to an array.

    
05.11.2015 / 13:02
5

It would be interesting to have a block serve-side to have a block cliente-side so that the user can make the correct corrections is to send the comment without any prohibited words.

If you value a readable text, doing so becomes indispensable, since deleting a word x may change the nexus of the comment.

Here is an example of% of% of the block, basically it will only send js if it has no forbidden words. you can improve the return message for 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>
    
05.11.2015 / 13:30
2

You can also use a table in the database.

Create a table, for example:

Words

  

Columns

     

ID | Wrong Word | The Right Word

Sign all the wrong words in the Wrong Word column and in the other Word Right column, sign up for a word that you want to replace the wrong one or just leave it blank. p>

When registering the user's message in the table, make a while in this table using 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.

    
05.11.2015 / 12:58
2

No Codeigniter has the helper text which has a word_censor function 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);
    }
}

usage example:

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

example running on ideone

ideone     
05.11.2015 / 13:00