Search code examples
phpregexeuro

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?


Solution

  • 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.