Daniel Rusu
Daniel Rusu

Reputation: 115

How to write regular expression in PHP to find prices / dollar values?

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

Answers (5)

stema
stema

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

FtDRbwLXw6
FtDRbwLXw6

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

renato
renato

Reputation: 125

preg_match_all("#- (\$\d+)#",$txt,$matches);
print_r($matches);

to match decimals:

preg_match_all("#- (\$\d+(?:\.\d+)?)#",$txt,$matches);

Upvotes: 5

aaaaaa
aaaaaa

Reputation: 2618

Try that :

\$[0-9]+(\.[0-9]+)?

This will match $4545 and $4545.45

Upvotes: 0

Rolando Cruz
Rolando Cruz

Reputation: 2784

My attempt at this:

$regex = "@(\$[\.0-9]+)@";

Upvotes: 0

Related Questions