RE: [PHP] Unable to match dollar sign in preg_match
| From: | Ford, Mike [LSS] | Date: | Tue, 24 Dec 2002 11:54:39 +0000 |
| Subject: | RE: [PHP] Unable to match dollar sign in preg_match | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-129277@lists.php.net to get a copy of this message | ||
> -----Original Message-----
> From: John W. Holmes [mailto:holmes072000@charter.net]
> Sent: 24 December 2002 00:44
>
> If you want to use some of PHP's special characters in your
> expression,
Don't you mean "preg's special characters"? Or even "PHP special characters
which are also preg special characters", as it's this duality of specialness that leads to
the necessity of double-escaping!
> such as $, you must escape it twice. For example:
>
> $matchme = "\$example";
> if (preg_match("/\$example/", $matchme)) {
>
> will not be matched because PHP interprets the \$ and passes it as $.
> Instead, you must do this:
>
> if (preg_match("/\\\$example/", $matchme)) {
This is the main reason I prefer to use *single*-quoted strings whenever possible in preg_ calls --
the above could more legibly be written as:
if (preg_match('/\$example/', $matchme)) {
This is an instance where I'd even tend to prefer to write single-quoted strings concatenated
to bare variables, rather than using double-quoted strings and variable-interpolation:
if (preg_match('/\$'.$example.'\./', $matchme)) {
rather than
if (preg_match("/\\\$$example\\./", $matchme)) {
Cheers!
Mike
---------------------------------------------------------------------
Mike Ford, Electronic Information Services Adviser,
Learning Support Services, Learning & Information Services,
JG125, James Graham Building, Leeds Metropolitan University,
Beckett Park, LEEDS, LS6 3QS, United Kingdom
Email: m.ford@lmu.ac.uk
Tel: +44 113 283 2600 extn 4730 Fax: +44 113 283 3211