-5

在 PHP 中,我想使用正则表达式通过以下公式修改具有重复字符的字符串:

 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

在此先感谢
巴勃罗

4

2 回答 2

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

解释:

  (            # 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

由于第 1 组和第 3 组位于交替的两侧,因此只有其中一个可以匹配。如果我们匹配一个组或“r”、“l”或“e”,那么第 1 组将包含“rr”、“ll”或“ee”。如果我们匹配任何其他字符的倍数,则第 3 组将包含该字符。

于 2013-05-10T20:10:08.977 回答
0

韦尔普,这是我的看法:

$content = preg_replace_callback(
  '~([^rle])(?:\1+)|([rle])(?:\2{2,})~i',
  function($m){return($m[1]!='')?$m[1]:$m[2].$m[2];},
  $content);
于 2013-05-10T20:47:17.133 回答