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
preg_match('/\$([0-9]+[\.,0-9]*)/', $str, $match);
$dollar_amount = $match[1];
will be probably the most suitable one
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
"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With