I have a little problem with my function:
function swear_filter($string){
$search = array(
'bad-word',
);
$replace = array(
'****',
);
return preg_replace($search , $replace, $string);
}
It should transform “bad-word” to “**” but the problem is the case sensivity
eg. if the user type “baD-word” it doesn’t work.
The values in your
$searcharray are not regular expressions.First, fix that:
Then, you can apply the
iflag for case-insensitivity:You don’t need the
gflag to match globally (i.e. more than once each) becausepreg_replacewill handle that for you.However, you could probably do with using the word boundary metacharacter
\bto avoid matching your “bad-word” string inside another word. This may have consequences on how you form your list of “bad words”.Live demo.
If you don’t want to pollute
$searchwith these implementation details, then you can do the same thing a bit more programmatically:(I’ve not used the recent PHP lambda syntax because codepad doesn’t support it; look it up if you are interested!)
Live demo.
Update Full code: