Reputation: 115
What's the PHP regular expression if I want to find all prices on a page?
So my page has something like:
2006 Ford F-250 Lariat - $20995
2005 BMW X3 3.0i***Silver SUV A Must SEE!#($(******* - $18950
2009 Chevrolet Impala LT - $15688
How can I write a regular expression to search for $ + any number of numbers after it?
Upvotes: 0
Views: 329
Reputation: 93086
This would be the correct regex to match a number starting with a $
with or without fraction, with or without separators. After the number a whitespace or the end of the line is required.
\$(?:\d{1,3}(,\d{3})*+|\d+)(?:\.\d{1,2})?(?=\s|$)
See it here on Regexr
This will match
$1
$1234
$1234567
$1.25
$1234
$1234.12
$1,123.1
$1,123.12
$12,123.1
$123,123.12
$123,123,123.12
But not
$1,12.12
$1.123
$1,1234
$.12
Upvotes: 0
Reputation: 28929
preg_match_all('/(\$\d{1,3}(,\d{3})*(\.\d{2})?)/', $page, $matches);
This will work for $999
and $999.99
formats, with or without separators.
Upvotes: 0
Reputation: 125
preg_match_all("#- (\$\d+)#",$txt,$matches);
print_r($matches);
to match decimals:
preg_match_all("#- (\$\d+(?:\.\d+)?)#",$txt,$matches);
Upvotes: 5