用PHP格式化欧元价格

时间:2015-11-25 17:38:38

标签: php regex euro

我尝试转换一些价格:

[0] => EUR 19,06 
[1] => 19, 70 € 
[2] => 42.53 €
[3] => 18€65 
[4] => 19,99 € 
[5] => 18€65
[6] => 23€95 
[7] =>      19,99 €  

采用以下格式:xx.xx€

我使用这个正则表达式:

/(EUR|)\s*(\d{1,})\s*(\.|,|€|€|)\s*(\d{1,}|)\s*(€|€| €| €|)\s*/

并将此掩码转换为preg_replace

$match = '${2}.$4 €';

除了第五个条目外,它的工作正常:19,99€。 这有什么问题?

1 个答案:

答案 0 :(得分:0)

我的正则表达式中没有任何错误,但可能会更短:

/^(?=.*(?:EUR|€|euro))\D*(\d+)\D*(\d*)\D*$/

面具

$match = '$1.$2 €';

解释

^                   # from start
(?=.*               # positive lookahead
    (?:EUR|€|euro)  # look for one of these
)                   # to take sure it is about € money
\D*(\d+)            # group at least + one digit in front of as many as possible non-digits
\D*(\d*)            # again to take the cents (* means zero or more)
\D*                 # take the remaining not digits
$                   # till the end

Regex live here.

希望它有所帮助。