views:

2008

answers:

5

Hi, 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....someone please help me with this....

A: 

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

You can also try

$tmpStr=preg_replace('/\$/', '\$', $tmpStr);
Ólafur Waage
I tried this...it did not work...:(
+5  A: 

I would strongly recommend using preg_quote() instead.

soulmerge
+1  A: 

The $ sign has to be escaped with itself so

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

I would also advise to look to addslashes instead.

Peter Smit
A: 

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

MiRAGe
+1  A: 

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