user3134277
user3134277

Reputation: 377

PHP : How to get repeated character in string

I have strings like this :

Aaaaaaaaa

I want to stop repeating just to 3 times, but not break the lowercase/uppercase, like this :

Aaa

My regex breaks the lowercase/uppercase :

$patternReplace = '/(.)\1{3,}/iu';    
$chaine = preg_replace($patternReplace, '$1$1$1', $chaine, -1 );

Result :

AAA

I want to get :

Aaa

thanx for help

Upvotes: 2

Views: 116

Answers (1)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Use subpatterns to get the additional backreferences(first subpattern is for the first character, the second subpattern - for the next two identical characters) :

$chain = "Aaaaaaaaa";
$patternReplace = '/(.)(\1{2})\1{1,}/iu';
$chain = preg_replace($patternReplace, '$1$2', $chain);

print_r($chain);  // "Aaa"

Upvotes: 1

Related Questions