3

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

2
  • You need to replace all but 3 letters? Commented Aug 2, 2013 at 12:42
  • possible duplicate of Regex to remove duplicate letters Commented Aug 2, 2013 at 12:43

2 Answers 2

6

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
Sign up to request clarification or add additional context in comments.

Comments

3

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

3 Comments

This I know, but its not correct. This will replace everything and only with single one. I need only A-Z, a-z.. And be replaced with three same letters.
Yes, thats now correct, also needed (.) to change to ([A-Za-z])
That's what I wrote in the last sentence, yes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.