Search code examples
phpregexnumber-formattingmagento-1.9

Add Thousand separator to any number even if it contains special characters


I have a site in Norwegian price format, so the product price displays like 1000,-.

It is a Magento based site, version ce-1.9.2.1.

Now I want to add thousand separator (most probably spaces but could be any character) to that price maintaining its format by using number_format function or regex, whichever maintains integrity best (like 1 000,- , 1 000 000,- etc.).

Anybody having any suggestions ?


Solution

  • Using lookarounds in preg_replace you can do this:

    $str = preg_replace('/\..*$(*SKIP)(*F)|(?<=\d)(?=(?:\d{3})+(?!\d))/', ' ', $str);
    

    \..*$(*SKIP)(*F) will ignore/skip part after DOT for this conversion.

    RegEx Demo