Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract dollar amount from string - regex in PHP

Tags:

regex

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

like image 734
ChicagoDude Avatar asked Nov 23 '11 18:11

ChicagoDude


3 Answers

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

will be probably the most suitable one

like image 79
Martin. Avatar answered Nov 04 '22 10:11

Martin.


Try this:

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
"
like image 10
FailedDev Avatar answered Nov 04 '22 10:11

FailedDev


You need this regular expression:

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

What is the function that meet your needs is up to you.

You can find then regex functions for PHP here: http://www.php.net/manual/en/ref.pcre.php

like image 4
KodeFor.Me Avatar answered Nov 04 '22 10:11

KodeFor.Me