Unformat money when parsing in PHP Unformat money when parsing in PHP php php

Unformat money when parsing in PHP


This is a bit more complex/ slow solution, but works with all locales. @rlenom's solution work only with dots as decimal separator, and some locales, like Spanish, use the comma as decimal separator.

<?phppublic function getAmount($money){    $cleanString = preg_replace('/([^0-9\.,])/i', '', $money);    $onlyNumbersString = preg_replace('/([^0-9])/i', '', $money);    $separatorsCountToBeErased = strlen($cleanString) - strlen($onlyNumbersString) - 1;    $stringWithCommaOrDot = preg_replace('/([,\.])/', '', $cleanString, $separatorsCountToBeErased);    $removedThousandSeparator = preg_replace('/(\.|,)(?=[0-9]{3,}$)/', '',  $stringWithCommaOrDot);    return (float) str_replace(',', '.', $removedThousandSeparator);}

Tests:

['1,10 USD', 1.10],['1 000 000.00', 1000000.0],['$1 000 000.21', 1000000.21],['£1.10', 1.10],['$123 456 789', 123456789.0],['$123,456,789.12', 123456789.12],['$123 456 789,12', 123456789.12],['1.10', 1.1],[',,,,.10', .1],['1.000', 1000.0],['1,000', 1000.0]

Caveats:Fails if the decimal part have more than two digits.

This is an implementation from this library:https://github.com/mcuadros/currency-detector


use ereg_replace

$string = "$100,000";$int = ereg_replace("[^0-9]", "", $string); echo $int;

outputs

1000000

function toInt($str){    return (int)preg_replace("/\..+$/i", "", preg_replace("/[^0-9\.]/i", "", $str));}

Update


<?php$string = array("$1,000,000.00","$1 000 000.00","1,000 000.00","$123","$123 456 789","0.15¢");foreach($string as $s) {    echo $s . " = " . toInt($s) . "\n"; }function toInt($str){    return preg_replace("/([^0-9\\.])/i", "", $str);}?>

Outputs

$1,000,000.00 = 1000000.00$1 000 000.00 = 1000000.001,000 000.00 = 1000000.00$123 = 123$123 456 789 = 1234567890.15¢ = 0.15

and if you cast it as an integer

<?php$string = array("$1,000,000.00","$1 000 000.00","1,000 000.00","$123","$123 456 789","0.15¢");foreach($string as $s) {    echo $s . " = " . _toInt($s) . "\n";    }function _toInt($str){    return (int)preg_replace("/([^0-9\\.])/i", "", $str);}?>

outputs

$1,000,000.00 = 1000000$1 000 000.00 = 10000001,000 000.00 = 1000000$123 = 123$123 456 789 = 1234567890.15¢ = 0

So there you have it. single line, one replace. you're good to go.


You can use

Example from Manual:

$formatter = new NumberFormatter('de_DE', NumberFormatter::CURRENCY);var_dump($formatter->parseCurrency("75,25 €", $curr));

gives: float(75.25)

Note that the intl extension is not enabled by default. Please refer to the Installation Instructions.