Remove repeating character

Use backrefrences

echo preg_replace("/(.)\\1+/", "$1", "cakkke");

Output:

cake

Explanation:

(.) captures any character

\\1 is a backreferences to the first capture group. The . above in this case.

+ makes the backreference match atleast 1 (so that it matches aa, aaa, aaaa, but not a)

Replacing it with $1 replaces the complete matched text kkk in this case, with the first capture group, k in this case.

Leave a Comment