问题
I have an Regex with me preg_match('/(?<=\$)\d+(\.\d+)?\b/', $str, $regs which return me the amount in a currency, but what i am trying is to get the symbol associated with the amount too.
1) E.g. the string is $300.00 asking price should return $300.00 but now it returns 300
2) E.g. the string is EUR 300.00 should return EUR300.00 but now it returns 300
Simply i want the currency with amount.
Thanks
回答1:
First, you match the currency which can be either $ or EUR, followed by optional white space:
(?:EUR|[$])\s*
Then, match the main digit group, followed by an optional period and two digits:
\d+(?:\.\d{2})?
In total we get this:
$pattern = '/(?:EUR|[$])\s*\d+(?:\.\d{2})?/';
if (preg_match($pattern, $string, $matches)) {
echo $matches[0];
}
回答2:
Try this one
$str = "$300.00 asking price";
preg_match('/^([\$]|EUR|€)\s*([0-9,\s]*\.?[0-9]{0,2})?+/', $str, $regs);
Outputs
array (size=3)
0 => string '$300.00' (length=7)
1 => string '$' (length=1)
2 => string '300.00' (length=6)
array (size=3)
0 => string 'EUR 300.00' (length=10)
1 => string 'EUR' (length=3)
2 => string '300.00' (length=6)
回答3:
Try with
/(\$|EUR)\s*(\d*\.\d+)?\b/
回答4:
If you want just the amount part for any Symbol :
preg_match_all("/([0-9]+[.]*)/", $t, $output_array);
$output_array=implode("",$output_array[0]);
" €12451.5651$Euro " will output: 12451.5651
来源:https://stackoverflow.com/questions/18404222/regex-to-get-currency-and-amount-from-string