2013-05-10 102 views
-4

在PHP欲修改已經由下式使用正則表達式重複字符的字符串:預先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

我不認爲土豚是太高興與此有關。 – 2013-05-10 20:06:27

+1

也不會木材。 – 2013-05-10 20:07:34

+1

讓我們不要爲此而展開大決戰,否則我們都會被殲滅! XD – 2013-05-10 20:16:36

回答

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組和gr oup 3在交替的兩側,只有其中一個可以匹配。如果我們匹配一個組或'r','l'或'e',則組1將包含'rr','ll'或'ee'。如果我們匹配任何其他字符的倍數,則組3將包含該字符。

+0

感謝您的幫助!工作完美! – 2013-05-10 20:51:02

+0

如果您將'\ 2 *'更改爲'\ 2 +',那麼交替的第二部分將匹配'ee'並將其替換爲'e'。 – 2013-05-10 20:56:27

+0

應該拋出一個'i'修飾符 – 2013-05-10 21:33:31

0

韋爾普,這是我的看法:

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