Reputation: 155
I continue to learn about PHP and PCRE. My question today is the following:
<?php
$search = "Money $ money $ money...";
/*I get "invalid"*/
if(preg_match("&money \$&", $search)){
echo 'Valid <br/>';
}else{
echo 'Invalid <br/>';
}
/*I get "valid"*/
if(preg_match('&money \$&', $search)){
echo 'Valid <br/>';
}else{
echo 'Invalid <br/>';
}
?>
I suppose when I use double quotes instead of single ones PHP is messing up with the encoding of ASCII character, but I do not totally understand why.
Can someone provide a detailed answer?
Upvotes: 2
Views: 55
Reputation: 1675
Single quote strings are not processed (not to the extent of double quote strings, to be precise) and are taken "as-is", but when a string is specified in double quotes, more special characters are available and variables are parsed within it.
If a dollar sign ($
) is encountered in a double quoted string, the parser will greedily take as many tokens as possible to form a valid variable name. So in the double quote string in the your code, the $
has some special meanings and does not represent the character of $
(the character of \
, also has some special meanings and is used to indicate the start of escape sequences).
To specify the literals of the dollar sign and the backslash in double quote strings, you need to use the escape sequences of \$
and \\
, respectively:
...
// Now, you will also get "valid" here
if(preg_match("&money \\\$&", $search)) {
...
Upvotes: 1