Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP正则表达式重复字符_Php_Regex - Fatal编程技术网

PHP正则表达式重复字符

PHP正则表达式重复字符,php,regex,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

在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
提前感谢
巴勃罗

说明:

  (            # 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组将包含该字符。

Welp,以下是我的看法:

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

我不认为土豚会对这件事感到太高兴。让我们不要为此开始一场世界末日,否则我们都会被消灭!我们玩得太开心了,谢谢你的帮助!工作完美!如果将
\2*
更改为
\2+
,则替换的第二部分将匹配
ee
,并替换为
e
。应添加
i
修饰符
$content = preg_replace_callback(
  '~([^rle])(?:\1+)|([rle])(?:\2{2,})~i',
  function($m){return($m[1]!='')?$m[1]:$m[2].$m[2];},
  $content);