Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace multiple same letters

Tags:

regex

php

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

like image 241
Legionar Avatar asked May 21 '26 17:05

Legionar


2 Answers

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
like image 56
falsetru Avatar answered May 24 '26 06:05

falsetru


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].

like image 37
Joey Avatar answered May 24 '26 05:05

Joey