I need to preg_replace multiple same letters (only A-Z or a-z, not numbers) in a row with same three. Can anybody help me with a pattern string?
Example:
Input: NO MEK PUCES CUDAK AVVVVVVVVVVVVVVVVVVVVVVVVV VASMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
Output: NO MEK PUCES CUDAK AVVV VASMAAA
Using group (([A-Za-z])) and backreference (\1).
$text = "NO MEK PUCES CUDAK AVVVVVVVVVVVVVVVVVVVVVVVVV VASMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
echo preg_replace('/([A-Za-z])\1{3,}/', "$1$1$1", $text);
# => NO MEK PUCES CUDAK AVVV VASMAAA
You can use a regular expression with a backreference:
preg_replace('/(.)\1+/', '$1', $str);
(.) matches any character and puts it in a capturing group. \1 is a reference to that same group, and + qualifies the previous token that it may appear once or more. So this replaces any run of at least two identical characters by just one.
If you want more than one character retained, like your example suggests, you can use the following:
preg_replace('/(.)\1{2,}/', '$1$1$1', $str);
If you need to restrict the character set, then just swap out the . by a character class, e.g. [a-zA-Z].
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With