简体   繁体   中英

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.

ie 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 ? :)

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.

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); }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM