user2217905
user2217905

Reputation:

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.

Upvotes: 2

Views: 7267

Answers (2)

samayo
samayo

Reputation: 16495

You do not need to create two or more instances of str_replace() since it is possible to replace as many words as possible using just one.

First, you must make a "group" of every bad word you wish to filter and put them inside an array.

# Example:

$bannedWords = array('shit', 'john mccain', 'jack and jill', 'IE6'); 

Then you might probably want to check first, if a variable includes a word from your list of banned words. For this you can use PHP's in_array() function:

if(in_array($_POST['keyword'], $bannedWords)){

   // keyword not allowed, 
}

After this, if you wish to replace the word, then use str_replace() as:

$replaced = str_replace($bannedWords, "", $_POST['keyword']);

This will remove all words and replace them with nothing, if you had passed "x" instead of "" as the second argument, then they would all have been replaced with x

# finally:

You can define a unique word to replace every unique banned word, by passing an array as the second argument of str_replace:

str_replace(['IE6', 'mccain', 'shit'], ['FireFox', 'roosevelt', 'Cake'], $_POST['keyword'])

Now from $_POST['keyword'] the word IE6 will be Replaced with FireFox with, mccain with roosevelt and so on..

Upvotes: 7

LegitSoulja
LegitSoulja

Reputation: 1

$remove = new Array("noob", "racist", "hate", "gay", "etc");
$text = str_replace($remove, "", $post);
echo $text;

This is a way of doing this. If you are getting the string from post, you can make a remove array, the make a text variable that replaces the array with a "" from the post. You can echo the text, NOT post, then any of the words that was in the array will not be show when the echo text is show.

Upvotes: 0

Related Questions