使用 preg_replace 替换字符,除非前面有转义字符
我正在尝试执行以下操作,希望有一位 reg_ex 专家能够提供一些启示。 我需要替换代码中的字符 [ 并将其设为 {。但在某些情况下, [ 需要保持 [ 而不是改变。所以我认为我需要使用
preg_replace("[", "{", $string);
具有合适的正则表达式的函数将导致使用前面没有转义字符的 [ 字符,例如 。 那么我怎样才能替换这个“[”而不是这个“[”呢?
预先非常感谢
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);
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 "["?
thanks a lot in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你可以做到这一点,它是通过一个约定调用否定后向断言
基本上,“仅当前面没有\时将[替换为{”
You can do this, and it's with a convention call negative lookbehind assertions
Basically, "replace [ with { only when not preceded by \"
为了完整起见:
如果您的正则表达式引擎很原始并且不知道如何执行此操作,还有另一种方法 负向后查找(PHP 不是这种情况):
这会捕获前面的字符,该字符仅限于
^
( start) 或[^\]
(任何非斜杠),并将其传递给替换。For completeness:
There another way to do this if your regexp engine is primitive and doesn't know how to do negative lookbehinds (which is not the case with PHP):
This captures the preceding character, which is restricted to
^
(start) or[^\]
(any non-slash), and passes it through the replace.