Home » Php » regex – How to escape $ in PHP using preg_replace?

regex – How to escape $ in PHP using preg_replace?

Posted by: admin July 12, 2020 Leave a comment


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?

How to&Answers:

I would strongly recommend using preg_quote() instead.


The correct answer is that you must escape the backslash and the dollar sign in the regex using PHP’s escape characters.

backslash = \
dollar sign = $

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

This is useful for anyone that needs to match a string that contains a dollar sign.


The $ sign has to be escaped with itself so

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

I would also advise to look to addslashes instead.


Looks like your problem is one of escaping. Single quotes (') in PHP work differently than double quotes ("). It’s a lot like in Perl, where variable interpolation does not happen in singly-quoted strings, and the dollar sign ($) is not a meta-character:

print "$"; # prints $
print '$'; # prints $

Also, Perl’s character classes will simplify your code:

$tmpStr = preg_replace('/([?#^&*()$\/])/', '\\$1', $tmpStr);


Yes, it does seem that \\$ is seen by PHP as $ in a double-quoted string.
That means you have to make PHP see a \$ by saying \\\$ .

I just tried preg_replace("/\\\$$k\\\$/", $v, $data) and indeed it works (replaces occurrences of $KEY$ with VALUE.


IIRC you replace $ with $. So it should be $$

You can also try

$tmpStr=preg_replace('/$/', '$', $tmpStr);


isn’t it true that PHP sees \$ as $ ?
I haven’t tested this out, it might go like this;

php is first, and replaces your “/\$/” with “/$/”
then the preg engine does it’s magic .. unfortunately, $ is a regular expression operator ( I believe it matches the end of a string?), so it doesn’t find the $-characters in your text but will

I think, what you need to do, is to doubble escape the $-character like so;

$tmpStr=preg_replace(“/\$/”, “\$”, $tmpStr);

Also .. in this case, I would have just used str_replace()


$pattern = preg_replace('/$(.+)/', '\$$1', $pattern);


In PHP, for the particular case of “$” used in HTML, you can also do a previous replace for its entity:

$tmpStr = str_replace('$', '$',$tmpStr);


Try a addslashes() ?

php.net / addslashes()