Better way to code this - Checking comment for banned word

376 Views Asked by At

Is there a better, faster way of doing the below?

This is a method from a class to check if a comment has a banned word in it, if so the comment needs to be manually approved.

I don't really want to change the way my models/database works so $this->get_words() ideally needs to stay (which returns an array of objects with properties generated form DB fields).

P.S I know profanity filters, etc are frowned upon but in this scenario it will just make a comment need manual approval.

public function check_string($str) {
    // Put banned words in an array
    $banned_words = [];
    foreach ($this->get_words() as $word) {
        $banned_words[] = $word->word;
    }

    $patterns = array(
        '/[_.-]/', '/1/', '/3/', '/4/', '/5/', '/6/',
        '/7/',     '/8/', '/0/', '/z/', '/@/'
    );
    $replacements = array(
        '',  'i', 'e', 'a', 's', 'g',
        't', 'b', 'o', 's', 'a'
    );

    // Turn str into array of individual words
    $str_words = explode(" ", $str);

    foreach ($str_words as $str_word) {
        $str_word = strtolower(preg_replace($patterns,$replacements,$str_word));
        if (in_array($str_word, $banned_words, true))
            return TRUE;
    }

    return FALSE;
}
2

There are 2 best solutions below

0
On

You can use this method

var bannedWords = ["NO", "NO NAME", "NONAME", "MISS", "MS", "MS.", "MR", "MR.", "MRS", "MRS."];

function checkBannedWords(value) {
            var rgx = new RegExp(bannedWords.join("|"), "gi");
            if (value.replace(rgx,'*').indexOf('*') != -1) {
                return false;
            }
            return true;
        }
3
On

you can place the bad word and the replacement word in a file. like this -

badword1,replaceword1
badword2,replaceword2
badword3,replaceword3

read the file like this and create an array of bad word and the replacement word-

$allline_arr = file('bad_word.txt');
$badword_arr = array();
foreach ($allline_arr as $line) {
    $badword_arr[] = explode(',', $line);
}

-OR-

$file = fopen("bad_word.txt","r");
$badword_arr = array();
while(! feof($file))
{
  $line = fgets($file);
  $badword_arr[] = explode(',', $line);
}
fclose($file);

now you can use it as you wish...