Escaping the dollar sign

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

Escaping the dollar sign

Post 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
jmut
Forum Regular
Posts: 945
Joined: Tue Jul 05, 2005 3:54 am
Location: Sofia, Bulgaria
Contact:

Post by jmut »

Code: Select all

preg_quote()
might be of interest.
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

Post 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.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.)
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

Post 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
User avatar
volka
DevNet Evangelist
Posts: 8391
Joined: Tue May 07, 2002 9:48 am
Location: Berlin, ger

Post by volka »

If you want to keep the double-quotes try

Code: Select all

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