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

Questions:

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.

Answer:

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.

Answer:

The $ sign has to be escaped with itself so

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

I would also advise to look to addslashes instead.

Answer:

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

Answer:

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.

Answer:

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

You can also try

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

Answer:

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

Answer:

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

Answer:

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

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

Answer:

Try a addslashes() ?

Check
php.net / addslashes()