preg_replace 只有一个字符但没有相邻的字符
preg_replace exactly one character but no adjacent ones
您好,我需要用双等号 (==Title==
) 替换 mediawiki H1 标记 (=title=
)。
但是我需要保持 Mediawiki H2 标记 (==title=
=) 不变。
所以如下:
=This is title= ==This is subtitle== ===This is sub sub title===
应该变成:
==This is title== ==This is subtitle== ===This is sub sub title===
使用:
preg_replace('/(\={1})(.*)\1/mU', '==\2==', $s);
然而我得到
==This is title== ====This is subtitle==== ======This is sub sub title======
我猜它也在贪婪地匹配捕获中出现的等号并将其加倍...
有人可以帮忙吗?
您可以使用环视:
$str = '=This is title= ==This is subtitle== ===This is sub sub title==='
$repl = preg_replace('/(?<!=)=(?!=)/', '==', $str);
//=> ==This is title== ==This is subtitle== ===This is sub sub title===
(?<!=)=(?!=)
将匹配 =
后跟没有 =
的 =
(?<!=)(=[^=]+=)(?!=)
您可以使用它并用 ==
替换它。参见演示。
您好,我需要用双等号 (==Title==
) 替换 mediawiki H1 标记 (=title=
)。
但是我需要保持 Mediawiki H2 标记 (==title=
=) 不变。
所以如下:
=This is title= ==This is subtitle== ===This is sub sub title===
应该变成:
==This is title== ==This is subtitle== ===This is sub sub title===
使用:
preg_replace('/(\={1})(.*)\1/mU', '==\2==', $s);
然而我得到
==This is title== ====This is subtitle==== ======This is sub sub title======
我猜它也在贪婪地匹配捕获中出现的等号并将其加倍... 有人可以帮忙吗?
您可以使用环视:
$str = '=This is title= ==This is subtitle== ===This is sub sub title==='
$repl = preg_replace('/(?<!=)=(?!=)/', '==', $str);
//=> ==This is title== ==This is subtitle== ===This is sub sub title===
(?<!=)=(?!=)
将匹配 =
后跟没有 =
=
(?<!=)(=[^=]+=)(?!=)
您可以使用它并用 ==
替换它。参见演示。