Page 1 of 1

Escaping the dollar sign

Posted: Tue Mar 06, 2007 7:28 am
by anjanesh
Hi

I cant seem to match something like '$5.50' from a string content using preg_match.

Code: Select all

$pattern = "#'\$(.*?)'#i";

if (preg_match($pattern, $content, $matches))
 {
 //
 }
Any idea why escaping the dollar isnt working ?

Thanks

Posted: Tue Mar 06, 2007 7:32 am
by jmut

Code: Select all

preg_quote()
might be of interest.

Posted: Tue Mar 06, 2007 7:50 am
by anjanesh
But I've given \$ in the pattern. I dont see why I need to use preg_quote().

Cant understand what really is the problem.
Had to replace $ with some text and match against the text instead !

Code: Select all

$str = str_replace('$', 'dollarsign', $str);
preg_match("#'dollarsign(.*?)'#i", $str, $matches);
Wierd.

Posted: Tue Mar 06, 2007 8:38 am
by feyd
You have a double quote string. \$ tells PHP to not attempt to replace the variable name following it. You need to do further escaping or use single quote strings (and still properly escape.)

Posted: Tue Mar 06, 2007 8:48 am
by anjanesh
Strange....Im pretty sure I tried using single quotes before..... ! (But I had tried with '##i' instead of '//i')

Code: Select all

$pattern = '/\'\$(.*?)\'/i';
Thanks

Posted: Tue Mar 06, 2007 11:03 am
by volka
If you want to keep the double-quotes try

Code: Select all

$pattern = "#'\\\$(.*?)'#i";
\\ -> \
\$ -> $
=> preg_match gets \$