在 PHP 中格式化欧元价格

Formatting Euro prices in PHP

我尝试转换一些价格:

[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 = '. €';

除了第 5 个条目:19,99 欧元外,它运行良好。 这有什么问题吗?

我在你的正则表达式中没有看到任何错误,但它可以更短:

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

作为掩码:

$match = '. €';

解释:

^                   # 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.

希望对您有所帮助。