Regex to get currency and amount from string

守給你的承諾、 提交于 2021-02-04 14:01:48

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!