Extraction of dollar amount from string - regular expression in PHP

I am trying to do this reliably for all possible strings.

Here are the possible values โ€‹โ€‹of $ str:

There is a new target price for $ 66
New target of $ 105.20 There is a new target price of $ 25.20.

I want the new $ dollar_amount to only extract the dollar amount from the above lines. e.g. $ dollar_amount = 66 / 105.20 / 25.20 in the above cases. How can I do this with a regex expression in PHP? Thanks

+8
php regex
source share
4 answers
preg_match('/\$([0-9]+[\.]*[0-9]*)/', $str, $match); $dollar_amount = $match[1]; 

will probably be the most suitable

+11
source share

Try the following:

 if (preg_match('/(?<=\$)\d+(\.\d+)?\b/', $subject, $regs)) { #$result = $regs[0]; } 

Explanation:

 " (?<= # Assert that the regex below can be matched, with the match ending at this position (positive lookbehind) \$ # Match the character "\$" literally ) \d # Match a single digit 0..9 + # Between one and unlimited times, as many times as possible, giving back as needed (greedy) ( # Match the regular expression below and capture its match into backreference number 1 \. # Match the character "." literally \d # Match a single digit 0..9 + # Between one and unlimited times, as many times as possible, giving back as needed (greedy) )? # Between zero and one times, as many times as possible, giving back as needed (greedy) \b # Assert position at a word boundary " 
+9
source share

You need this regular expression:

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

Which function meets your needs is up to you.

Here you can find the regular expression functions for PHP: http://www.php.net/manual/en/ref.pcre.php

+3
source share

try

 #.+\$(.+)\s.+# 

0
source share

All Articles