I’m running into a bit of an issue when it comes to matching subpatterns that involve the dollar sign. For example, consider the following chunk of text:
Regular Price: $20.50 Final Price: $15.20
Regular Price: $18.99 Final Price: $2.25
Regular Price: $11.22 Final Price: $33.44
Regular Price: $55.66 Final Price: $77.88
I was attempting to match the Regular/Final price sets with the following regex, but it simply wasn’t working (no matches at all):
preg_match_all("/Regular Price: \$(\d+\.\d{2}).*Final Price: \$(\d+\.\d{2})/U", $data, $matches);
I escaped the dollar sign, so what gives?
Inside a double quoted string the backslash is treated as an escape character for the
$. The backslash is removed by the PHP parser even before thepreg_match_allfunction sees it:Output (ideone):
"/Regular Price: $(\d+\.\d{2}).*Final Price: $(\d+\.\d{2})/U" ^ ^ the backslashes are no longer thereTo fix this use a single quoted string instead of a double quoted string:
See it working online: ideone