1

I've got this if statement that checks for these "Offensive words" in an input of types = text

if(strstr($key,'bi**h') || strstr($key,'fu**k') || strstr($key,'son of a   bit**') || strstr($key,'cun*') || strstr($key,'fuc**r') || strstr($key,'mother fuc**') || strstr($key,'shi**') || strstr($key,'cr**p') ){

      $erros['insult']='please avoid any offending words';

       }

This code is made by another developer, I was just wondering is there any more way other than adding the double pipes for each word I have to enter?. It kinda looks a primitive way of writing such a code, I guess.

MaryBaker
  • 667
  • 1
  • 5
  • 8
  • One problem is, if you really want to try to avoid offending words, you'll need to put a lot more of them in there. Looping over an array of patterns to match would make for more manageable code than a bunch of ORs. – Don't Panic Jul 20 '16 at 20:16
  • Check [this answer](http://stackoverflow.com/questions/6284553/using-an-array-as-needles-in-strpos). – mister martin Jul 20 '16 at 20:19
  • Does the " OR || " have any down side or not recommended to be used in such a way in a code other than being messy and not manageable ? – MaryBaker Jul 20 '16 at 20:21
  • If you use strstr, make sure that you will check their types as well. Since var_dump((bool)strstr('10', '0')) === false. So always user if(strstr('10', '0') !== false) – Wesley Abbenhuis Jul 20 '16 at 20:29

2 Answers2

1

Be careful with bad word filters, what about the word shitake? Here's a simple way to replace bad words and check against the original string:

$bad = array('bi**h', 'fu**k', 'son of a   bit**', 'cun*', 'fuc**r', 'mother fuc**', 'shi**', 'cr**p');

if(str_replace($bad, '', $key) != $key) {
      $erros['insult']='please avoid any offending words';
}

However the if and || approach will be faster.

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
-1

I guess you either stick to strstr/strpos with ORs, or use regular expressions. I would recommend avoid regexps if you've got an enumerable list of stop words.

Nik P
  • 89
  • 7