除非前面有转义字符,否则使用 preg_replace 替换字符 [英] use preg_replace to replace character unless an escape character precedes
问题描述
我正在尝试执行以下操作,希望周围有 reg_ex 专家可以提供一些帮助.我需要替换代码中的字符 [ 并将其设为 {.但在某些情况下, [ 需要保持为 [ 而不会改变.所以我认为我需要使用
i'm trying to do the following hope there's a reg_ex expert around to shed some light. I need to replace the character [ in my code and make it a {. But there is cases where the [ needs to remain a [ and not change. So the way i figured it is i need to use the
preg_replace("[", "{", $string);
preg_replace("[", "{", $string);
具有合适的正则表达式的函数将导致 [ 前面没有要使用的转义字符的字符可以说 .那么我怎样才能替换这个["而不是这个["?
function with a suitable regular expression that will result the [ characters that are not preceded by the escape character to be used lets say . So how can i get to replace this "[" and not this "["?
非常感谢
推荐答案
你可以做到这一点,它是一个约定调用否定后视断言
You can do this, and it's with a convention call negative lookbehind assertions
echo preg_replace( "/(?<!\\\\)\\[/", '{', "\[ [ [ \[ [" );
基本上,仅当前面没有 \"时才将 [ 替换为 {
Basically, "replace [ with { only when not preceded by \"
这篇关于除非前面有转义字符,否则使用 preg_replace 替换字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!