如何使用preg_replace在PHP中转义$? [英] How to escape $ in PHP using preg_replace?

查看:80
本文介绍了如何使用preg_replace在PHP中转义$?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用preg_replace来转义特殊字符:

I am using preg_replace to escape special characters:

$tmpStr=preg_replace("/\?/", "\?", $tmpStr);
$tmpStr=preg_replace("/\#/", "\#", $tmpStr);
$tmpStr=preg_replace("/\^/", "\^", $tmpStr);
$tmpStr=preg_replace("/\&/", "\&", $tmpStr);
$tmpStr=preg_replace("/\*/", "\*", $tmpStr);
$tmpStr=preg_replace("/\(/", "\(", $tmpStr);
$tmpStr=preg_replace("/\)/", "\)", $tmpStr);
$tmpStr=preg_replace("/\//", "\/", $tmpStr); 

但是我无法使用相同的功能对$进行转义:

But I am not able to escape $ using the same function:

$tmpStr=preg_replace("/\$/", "\$", $tmpStr);

另外,当我使用上述语句时,所有空格都被$替换,并且$未被转义.

And also when I use the above statement all the spaces get replaced by $ and $ is not getting escaped.

如何正确避开美元符号?

How do I escape the dollar sign correctly?

推荐答案

我强烈建议使用 preg_quote().

这篇关于如何使用preg_replace在PHP中转义$?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆