Hasan Zohdy
Hasan Zohdy

Reputation: 111

PHP Replace any repeated letters with less number of letters

I would like to reduce a sequence of the same 5 repeating numbers or letters to a sequence of the same 2 repeating numbers or letters.

i.e aaaaa => aa

Problem:

I am unsure on what parttern to put in the preg_replace() parameters.

Example:

preg_replace('/[a-zA-Z0-9]{5}/','/[a-zA-Z0-9]{2}/',$str);

Any Ideas about this ? :)

Upvotes: 0

Views: 87

Answers (2)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89567

You need to use a capture group and a backreference:

$str = preg_replace('~([a-zA-Z0-9])\1{4}~', '$1$1', $str);

or

$str = preg_replace('~([a-zA-Z0-9])\1\K\1{3}~', '', $str);

details pattern 1:

~                # pattern delimiter
(                # open the capture group 1
    [a-zA-Z0-9] 
)                # close the capture group 1
\1{4}            # backreference: repeat 4 times the content of the capture group 1
~

In the replacement string $1 refers to the content of the capture group 1. (as \1 in the pattern)

The second pattern is not really different, it use only the \K feature that removes all on the left from the match result. With this trick, you don't need to put the two letters in the replacement string since they are preserved. Only the last 3 letters are replaced.

Upvotes: 3

mti2935
mti2935

Reputation: 12027

Here's a way to do it with simple string functions and basic programming constructs:

$str="aaaaa 11111 bbbbb";
for($ascii=32;$ascii<=126;$ascii++) {
  $char=chr($ascii);
  $charcharcharcharchar=$char . $char . $char . $char . $char;
  $charchar=$char . $char;
  if(strpos($str, $charcharcharcharchar) !== FALSE) { $str=str_replace($charcharcharcharchar, $charchar, $str); }
}

Upvotes: 0

Related Questions