Laim Laim - 1 year ago 56
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 Source

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, can use the in_array() function like

if(in_array($post, $BadWords)){
   //bad word is found so, do something
  //the post is ok.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download