use preg_replace to replace character unless an escape character precedes

故事扮演 提交于 2020-01-21 12:23:05

问题


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


回答1:


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 \"




回答2:


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):

$str = preg_replace( "/(^|[^\\\\])\\[/", '$1{', $str );

This captures the preceding character, which is restricted to ^ (start) or [^\] (any non-slash), and passes it through the replace.



来源:https://stackoverflow.com/questions/1374643/use-preg-replace-to-replace-character-unless-an-escape-character-precedes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!