Duplicate question

How can I avoid $ in the replaced section in the following expression?

$tmp_code = preg_replace('/(<\?=\$([a-zA-Z0-9\_]+)\?>)/me','"{$$2}"',$tmp_code);

The replacement text should like {$ test}, but I can't figure out how to avoid the first $. I tried \ $ but did nothing.

+3
source share
1 answer

As a rule of thumb, you should prefer an preg_replace_callbackexpression modifier /e. But depending on what you want to do, there are many workarounds.

You can split the string expression:

 '"{"."$"."$2"."}"', $tmp

Or use an alternate placeholder syntax and exit {$so that it is not interpreted as a variable in double quotes:

 '"{\\\$\2}"'

(No, I didn’t know this, I was just messing around.)

+2
source

All Articles