PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
$badwords = array ("badword1", "badword2", "badword3");
$userpost = "i like to say things like badword1 because blah and then more blah.";
How do I search for any of the words in $badwords array? I think there is a method that can do this. I know I could do a foreach loop but I would rather keep it simple and use the function which does this for me.
$badwords = array ("badword1", "badword2", "badword3");
$goodwords = array ("goodword1", "goodword2", "goodword3");
$userpost = "i like to say things like badword1 because blah and then more blah.";
$grated = str_replace($badwords, $goodwords, $userpost);
echo $grated;
Also note that this example is actually in the PHP manual for the str_replace function ( http://us3.php.net/str_replace )
Just a note, if you want all the badwords replaced with a single censory word, it is not neccesary to pass an array of replacements. Secondly, you should consider using the case insensitive str_ireplace()
$userpost = "i like to say things like badword1 because blah and then more blah.";
$badwords = array ("badword1", "badword2", "badword3");
$grated = str_ireplace($badwords, 'smurf', $userpost);
echo $grated;
Yes, thanks a bunch for the replies. I briefly skimmed the php doc and didn't notice that one did allow for arrays. I knew I had seen it and used it before. I just kept seeing functions that only allowed strings.. Thanks a bunch.
Okay actually I remember why I didn't use the str_replace. I want to run an if statement to check if the string contains any of the badwords from the $badwords array. Note the code below does not work. The php manual says if the needle is not a string it is converted into an int. "If needle is not a string, it is converted to an integer and applied as the ordinal value of a character. "
If you want to see which words were actually caught, you can add a 3rd parameter $matches and use preg_match_all() instead.
Also, in your solution you still did not take case sensitity into consideration, as I have already mentioned. You need to use the string insentive alternatives.