正则表达式模式,忽略字符

时间:2016-05-24 18:02:55

标签: php regex preg-replace

寻找一个检测单个字符(特定)的正则表达式模式,但在进入double或triple时忽略它... N。

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

我想替换单个字符,但在重复时忽略它们。

期望的结果(替换单个&#39; c&#39; FOO&#39;)

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

提示:我知道如何做相反的事情 - 替换双倍但忽略单身

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

1 个答案:

答案 0 :(得分:2)

您可以使用lookarounds

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

如果两边都没有被c包围,则表示匹配c

RegEx分手:

(?<!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);