views:

48

answers:

1

Looking for a reg ex to null (empty) the string if it any contains the bad word..

    $string1 = "Ihatestackoverflow";
    $string2 = "I HaTe sackoverflow";
    $string3 = "1HaTestackoverflow";

    $badword = "hate";

# result
# string1 = "";
# string2 = "";
# string3 = "";
+2  A: 
$regex = '#^.*?(hate).*$#ims';
$str = preg_replace($regex, '', $str);

To add more "bad words", just add them in the ():

$regex = '#^.*?(hate|anotherbadword|yetanother|etc).*$#ims';

The leading ^ and trailing $ match the full string. The i option is for case insensitive matching. The m enables multi-line mode (so that ^ and $ match the whole string, as opposed to a single line in it). The s enables DOTALL (so the . matches new line characters as well).

You could

ircmaxell
as an alternative you can store all the words you don't want in an array and iterate them. `$bad = array(...); for ($i = 0; $i < count($bad) $i++) { $str = preg_replace('#^.*?(' . $bad[$i] . ').*$#ims', '', $str); }` (far more readable on multiple lines but it doesn't qualify as a separate answer as that'd be stealing :)
Matt S
@Matt S: IF you were going to use a loop, I'd use `stripos()`... Something like `foreach($bad as $word) { if (stripos($string, $word) !== false) { $string = ''; break;} }`. The break is so that once you kill the string, you don't continue the loop. Or you could build the regex from the loop: `$regex = '#^.*?('; foreach ($bad as $word) { $regex .= preg_quote($word, '#') . '|'; } $regex = rtrim($regex, '|') . ').*$#ims';`...
ircmaxell
Correct, personally I dislike the use of breaks in my statements which is why I used the `for ()` instead of the `foreach ()`. You of course are correct on the `stripos` being a better choice than a regex.
Matt S