Laim Laim - 5 months ago 8
PHP Question

PHP, filter specific words using str_replace

Basically, I currently have this line of code:

$uname = str_replace(array('!','"','£','$','%','%','^','&','*','(',')','-','+','=','\\','/','[',']','{','}',';',':','@','#','~','<',',','>','.','?','|',' '), '', $uname);


I know it is messy, I've never used it before in this 'context'

Anyway, is there anyway I could have another array for bad words? example:

$uname = str_replace(array)('!','"','£','$','%','%'), '', $uname);
str_replace(array)('badword1','badword2'), '****', $uname);


The above is basically what I want, however if their is a neater way to do it Ill do it like that, however any help is welcome.

Answer

No need to create two str_replace()'s or clutter your code.

This basically, will allow you to replace all bad words with one good word

say $text handles your input. now, neater way would be

$name = str_replace(array('hate','racism','stupidity'), "love", $text);

Additional Edit

If you want to keep a clean-list of "bad words separately" then, create an array

$BadWords = array('fk','shit','idiot','foo','foo','foo');

then considering $post is a value submitted by user, ..you can use the in_array() function like

if(in_array($post, $BadWords)){
   //bad word is found so, do something
}else{
  //the post is ok.
}
Comments