2016-05-24 126 views
-1

尋找該檢測(特定)單個字符正則表達式模式的雙外觀,而且進來兩倍或三倍的時候忽略它正則表達式模式... N忽略字符

abcde <- looking for this (c's separated by another character) 
abccdce <- not this (immediately repeating c's) 

我想要替換單個字符,但在重複時忽略它們。

期望的結果(更換一個 'c' 與 '富')

abcde -> abFOOde 
abccdce -> abccdce 
abcdeabccde ->abFOOdeabccde 

提示:我知道該怎麼做相反的事情 - 取代雙卻忽略單打

$pattern = '/c\1{1}/x'; 
$replacement = 'FOO'; 
preg_replace($pattern, $replacement, $text); 
+0

爲什麼 「abccdce」 不會產生 「abccdFOOe」?因爲在正則表達式模式中寫入'{1}'總是無用的。 –

回答

2

您可以使用lookarounds爲此:

(?<!c)c(?!c) 

這意味着匹配c如果沒有包圍c兩邊。

正則表達式破碎:

(?<!c) # negative lookbehind to fail the match if previous position as c 
c  # match literal c 
(?!c) # negative lookahead to fail the match if next position as c 

代碼:

$repl = preg_replace('/(?<!c)c(?!c)/', 'FOO', $text); 
+0

@fatfish:這個工作適合你嗎? – anubhava