PHP正则表达式重复字符

时间:2013-05-10 20:04:53

标签: php regex

在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

提前致谢
巴勃罗

2 个答案:

答案 0 :(得分: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组将包含该字符。

答案 1 :(得分:0)

Welp,这是我的看法:

$content = preg_replace_callback(
  '~([^rle])(?:\1+)|([rle])(?:\2{2,})~i',
  function($m){return($m[1]!='')?$m[1]:$m[2].$m[2];},
  $content);