Use preg_replace to replace a character if the preceding character

I am trying to make the following hope there, reg_ex expert, to shed some light. I need to replace the character [in my code and make it {. But there are cases when [should remain [and not change]. So, as I understand it, I need to use

preg_replace ("[", "{", $ string);

with a suitable regular expression that will cause [characters that are not preceded by the escape character to be used, say. So, how can I replace this with "[", and not this "[??

thanks in advance

+3
source share
2 answers

, lookbehind

echo preg_replace( "/(?<!\\\\)\\[/", '{', "\[ [ [ \[ [" );

, " [ { \

+4

:

, , lookbehinds ( PHP):

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

, ^ (start) [^\] ( - ) .

+1

Source: https://habr.com/ru/post/1716815/


All Articles