Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex escaping question

Tags:

regex

php

How can I escape the $ in the replaced section in the following statement?

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

The replaced text should like like {$test} however I can't figure out how to escape the first $. I've tried \$ but that didn't do anything.

like image 616
Joe Avatar asked Jan 17 '26 00:01

Joe


1 Answers

Generally you should prefer preg_replace_callback over the /e expression modifier. But depending on what you want to do, there are multiple workarounds.

You can split up the string expression:

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

Or use the alternative placeholder syntax and escape the {$ so it does not get interpreted as variable variable within the double quotes:

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

(No, I didn't know that. Just tinkered around.)

like image 86
mario Avatar answered Jan 19 '26 15:01

mario



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!