寻找一个检测单个字符(特定)的正则表达式模式,但在进入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);
答案 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);