0

I have an array $bad_words containing English rude words and their dotted out equivalents and I use preg_replace_callback as follows:

$bad_words = array(
    "badword" => "s••t",
    "badword2" => "f••k"
    ...
);

function filter_bad_words($matches)
{
    global $bad_words;
    $replace = $bad_words[$matches[0]];
    return isset($replace) ? $replace : $matches[0];
}

// $JSON is a string variable
preg_replace_callback('!\w+!', 'filter_bad_words', $JSON);

This solution is not case insensitive and I cant figure out what parameter to pass to the preg_replace_callback to make it case insensitive.

Thank you for help

John Doe
  • 983
  • 4
  • 14
  • 27
  • 1
    off topic, but if you must have a 'bad words filter', please be careful not to commit [the clbuttic mistake](https://duckduckgo.com/?q=clbuttic). (your current code looks like it's quite likely to do so). – Spudley Jan 21 '14 at 13:46
  • clbuttic mistake itself is handeled however a directly opposite problem is not. If a name or a word contains a swear word the function does not replace it however if a user was to join two swear words such as fu***ngcu*t the function will fail to replace either word. Is there even a solution for this? – John Doe Jan 21 '14 at 13:53
  • 2
    There is no real good technical solution for this, because it is not a technical problem, but a social one. If you don’t like me calling you a _mothertrucker_, then I’ll write _m.o.t.h.e.r.t.r.u.c.k.e.r_ or something like this instead … – CBroe Jan 21 '14 at 14:19
  • @ahojvole just use `strtolower()`, something like `$replace = $bad_words[strtolower($matches[0])];` – HamZa Jan 22 '14 at 23:02

1 Answers1

0

Don't forget to put the g modifier right next to the i modifier (mentioned in the answer of rid) when you are checking strings instead of single words. Otherwise if there are more bad words in a sentence, it will just stop after the first one.

Edit: Just saw that user rid deleted his answer, but you can make it case-insensitive by using the i-modifier.

http://www.regular-expressions.info/modifiers.html

Douwe de Haan
  • 6,247
  • 1
  • 30
  • 45
  • 1
    There is no `g` modifier in PHP. When replacing, php will automatically replace all. When matching, instead of using `preg_match()` you would use `preg_match_all()` to match all (globally). – HamZa Jan 22 '14 at 23:05
  • 1
    My bad, you're right. I'm using way too much JavaScript these days... – Douwe de Haan Jan 24 '14 at 09:36