简体   繁体   中英

Formatting Euro prices in PHP

I try to convert some prices:

[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 €  

into this format: xx.xx €

I use this regex:

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

and this mask into a preg_replace :

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

It worked fine EXCEPT with the 5th entry: 19,99 €. What is wrong with this?

I don't see any errors in your regex, but it could be shorter:

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

and as mask :

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

Explaining:

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

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM