views:

30

answers:

1

I often have comment forms and lots of users post things such as !!!!!!!!!!! and ??????????, and I want to use preg_replace to change them to !! and ??, with two maximum.

Any idea how to do this? Thanks in advance.

+3  A: 
$t = "aaaaaabbbbbbbbccccccccccc";
$t = preg_replace('~(.)\1{2,}~', '$1$1', $t);
echo $t; // aabbcc
stereofrog
Shouldn't it be `{2,}`? Otherwise it would require 4 in a row to trigger (instead of the question's 3 in a row)...
ircmaxell
@ircmaxell, correct, thanks
stereofrog
+1, I just wanted to make sure I was reading it right (and you weren't taking advantage of something that I didn't understand)...
ircmaxell
Thanks for this code. Works great :)
Tech163