[ACCEPTED]-How to escape $ in PHP using preg_replace?-preg-replace
The correct answer is that you must escape 4 the backslash and the dollar sign in the 3 regex using PHP's escape characters.
backslash = \\
dollar sign = \$
$tmpStr=preg_replace("/\\\$/", "\\$", $tmpStr);
This 2 is useful for anyone that needs to match 1 a string that contains a dollar sign.
Looks like your problem is one of escaping. Single 6 quotes ('
) in PHP work differently than double 5 quotes ("
). It's a lot like in Perl, where 4 variable interpolation does not happen in 3 singly-quoted strings, and the dollar sign 2 ($
) is not a meta-character:
print "\$"; # prints $
print '\$'; # prints \$
Also, Perl's 1 character classes will simplify your code:
$tmpStr = preg_replace('/([?#^&*()$\\/])/', '\\\\$1', $tmpStr);
The $ sign has to be escaped with itself 1 so
$tmpStr=preg_replace("/$$/", "\$", $tmpStr);
I would also advise to look to addslashes instead.
Yes, it does seem that \\$
is seen by PHP as 4 $
in a double-quoted string.
That means you 3 have to make PHP see a \$
by saying \\\$
.
I just 2 tried preg_replace("/\\\$$k\\\$/", $v, $data)
and indeed it works (replaces occurrences 1 of $KEY$
with VALUE.
IIRC you replace $ with $. So it should 1 be $$
You can also try
$tmpStr=preg_replace('/\$/', '\$', $tmpStr);
isn't it true that PHP sees \$ as $ ? I 11 haven't tested this out, it might go like 10 this;
php is first, and replaces your "/\$/" with 9 "/$/" then the preg engine does it's magic 8 .. unfortunately, $ is a regular expression 7 operator ( I believe it matches the end 6 of a string?), so it doesn't find the $-characters 5 in your text but will
I think, what you 4 need to do, is to doubble escape the $-character 3 like so;
$tmpStr=preg_replace("/\$/", "\$", $tmpStr);
Also 2 .. in this case, I would have just used 1 str_replace()
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.