当前位置: 动力学知识库 > 问答 > 编程问答 >

regex - PHP regular expression repeated chars

问题描述:

In PHP I want to modify a string that has repeated chars by the following formula using regular expressions:

 1. Chars different from "r", "l", "e" repeated more than once

consecutively should be replaced for the same char only one time.

Example:

- hungryyyyyyyyyy -> hungry.

- hungryy -> hungry

- speech -> speech

2. Chars "r", "l", "e" repeated more than twice replaced for the same

char twice.

Example:

- greeeeeeat -> greeat

Thanks in advance

Pablo

网友答案:
preg_replace('/(([rle])\2)\2*|(.)\3+/i', "$1$3", $string);

Explanation:

  (            # start capture group 1
    ([rle])      # match 'r', 'l', or 'e' and capture in group 2
    \2           # match contents of group 2 ('r', 'l', or 'e') again
  )            # end capture group 1 (contains 'rr', 'll', or 'ee')
  \2*          # match any number of group 2 ('r', 'l', or 'e')
|            # OR (alternation)
  (.)          # match any character and capture in group 3
  \3+          # match one or more of whatever is in group 3

Since group 1 and group 3 are on opposite sides of the alternation, only one of them can ever match. If we are matching a group or 'r', 'l', or 'e' then group 1 will contain 'rr', 'll', or 'ee'. If we are matching multiples of any other character then group 3 will contain that character.

网友答案:

Welp, here's my take:

$content = preg_replace_callback(
  '~([^rle])(?:\1+)|([rle])(?:\2{2,})~i',
  function($m){return($m[1]!='')?$m[1]:$m[2].$m[2];},
  $content);
分享给朋友:
您可能感兴趣的文章:
随机阅读: