use preg_replace to replace character unless an escape character precedes

php, preg-replace, regex

Solution

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

Problem

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

Original source