Reputation: 341
why in the following code, in order to match the string, then we have to escape the '$' with two backslashes and not one?
<?php
$text = "$3.99";
preg_match_all("/\\$\d+\.\d{2}/", $text, $matches) ;
var_dump($matches) ;
?>
output: array (size=1)
0 =>
array (size=1)
0 => string '$3.99' (length=5)
what is the matching rule for the pattern: "/\$\d+.\d{2}/" (one backslash)
Upvotes: 2
Views: 83
Reputation:
I think php has a few options for depicting the regex string.
At the first level, they seem to want strings of some sort because
they don't have quote like operators like Perl, at least I don't think so.
Level 2, they move on to the regex delimiter (stay away from double quotes as delimiter).
Level 3, the raw regex is left bare after 1 & 2 are done.
So usually, you have reverse the process 3 - 2 -1, and present that to the php source code.
A note - Regex delimiters are a tricky business. In level 2, it is possible that you could
choose a delimiter that is un-escapable in the regular expression. In your case '$
' would
not be a viable delimiter.
Some possibilities might help you...
\$\d+\.\d{2} # raw regex
/\$\d+\.\d{2}/ # no quote, using '/' for delimeter
'/\$\d+\.\d{2}/' # single quotes ""
"/\\$\\d+\\.\\d{2}/" # double quotes ""
~\$\d+\.\d{2}~ # no quote, using '~' for delimeter
'~\$\d+\.\d{2}~' # single quotes ""
"~\\$\\d+\\.\\d{2}~" # double quotes ""
Upvotes: 0
Reputation: 18550
http://php.net/manual/en/language.types.string.php
From the docs
If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:
Then
\\ backslash
\$ dollar sign
So the double backslash is for the string not the regex
A single backslash would result in the $ literal which is then passed to the regex
Upvotes: 2