Search code examples
phpregexnumber-formatting

PHP replace currency in a string


I am trying to format a string in order to get a number. I have tried different methods however, when I try to remove the symbol I get a series of numbers instead. What am I doing wrong?

$sn_get_full_price = "€12.000,0";
$sn_get_full_price_no_comma = preg_replace('/^([^,]*).*$/', '$1',$sn_get_full_price);
$sn_get_n_price = preg_replace('/[^\d,\.]/', '',$sn_get_full_price_no_comma);

the result I have is 836412.000 instead of 12000.

Also there is a way to to this with one line of code?


Solution

  • The reason is that your real string is "€12.000,0" with the € symbol written as an html entity (display the source code of your html page to be convinced).

    To solve that you can use:

    echo str_replace(['€', ',0'], '', $yourstring);
    

    You can also use your actual code, except that you have to convert the entities before (with html_entity_decode()) and to add the u modifier to your patterns (in particular the second one).