How to escape $ in PHP using preg_replace?

sakura picture sakura · Apr 20, 2009 · Viewed 26.9k times · Source

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?

Answer

soulmerge picture soulmerge · Apr 20, 2009

I would strongly recommend using preg_quote() instead.