开发者

Regex escaping question

开发者 https://www.devze.com 2023-03-12 23:38 出处:网络
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);

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 {$te开发者_开发知识库st} however I can't figure out how to escape the first $. I've tried \$ but that didn't do anything.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消