ChicagoDude ChicagoDude - 1 month ago 6
PHP Question

Extract dollar amount from string - regex in PHP

i am hvaing a challenge trying to do this reliably for all possible strings.

Here are the possible values of $str:


There is a new $66 price target

There is a new $105.20 price target

There is a new $25.20 price target



I want a new $dollar_amount to extract just the dollar amount from the above sample strings. e.g. $dollar_amount = 66/105.20/25.20 in above cases. How can i reliably do this with a regex statement in PHP? Thanks

Answer
preg_match('/\$([0-9]+[\.]*[0-9]*)/', $str, $match);
$dollar_amount = $match[1];

will be probably the most suitable one

Comments