Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
552 views
Welcome To Ask or Share your Answers For Others

1 Answer

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 the preg_match_all function sees it:

$r = "/Regular Price: $(d+.d{2}).*Final Price: $(d+.d{2})/U";
var_dump($r);

Output (ideone):

"/Regular Price: $(d+.d{2}).*Final Price: $(d+.d{2})/U"
                 ^                           ^
              the backslashes are no longer there

To fix this use a single quoted string instead of a double quoted string:

preg_match_all('/Regular Price: $(d+.d{2}).*Final Price: $(d+.d{2})/U',
               $data,
               $matches);

See it working online: ideone


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...