What a quick way to clear a money line

Possible duplicate:
PHP: unformat money

How to get rid of anything that is not a number or a point, replacing ,on .with a light regular expression?

Examples:

$50.45     = 50.45
USD 50.45  = 50.45
50,45      = 50.45
USD$ 50.45 = 50.45
+5
source share
4 answers
<?php
$money = array(
    '$50.45',
    'USD 50.45',
    '50,45',
    'USD$ 50.45'
);

// remove everything except a digit "0-9", a comma ",", and a dot "."
$money = preg_replace('/[^\d,\.]/', '', $money);

// replace the comma with a dot, in the number format ",12" or ",43"
$money = preg_replace('/,(\d{2})$/', '.$1', $money);

print_r($money);
?>

Conclusion:

Array
(
    [0] => 50.45
    [1] => 50.45
    [2] => 50.45
    [3] => 50.45
)
+5
source
preg_replace('/.*?(\d+)(?:[.,](\d+))?.*/', '\1.\2', $string);
+1
source

, , :

preg_replace("([^0-9\.])","",str_replace(",",".",$val));

, , . , / .

script:

$inputs = array("\$50.45", "USD 50.45", "50,45", "USD\$ 50.45");

foreach ($inputs as $val) {
    $cleanVal = preg_replace("([^0-9\.])","",str_replace(",",".",$val));
    echo "GIVEN: <b>".$val."</b> -> CLEAN: <b>".$cleanVal."</b><br/>";    
}

:

: $50,45 → : 50,45

: 50,45 → : 50,45

: 50,45 → : 50,45

: 50,45 → : 50,45

+1

(demo):

$money = array(
    '$50.45',
    'USD 50.45',
    '50,45',
    'USD$ 50.45'
);

foreach ($money as $val) {
    echo filter_var(
        str_replace(',', '.', $val),
        FILTER_SANITIZE_NUMBER_FLOAT,
        FILTER_FLAG_ALLOW_FRACTION
    ), PHP_EOL;
}

// gives 
// 50.45
// 50.45
// 50.45
// 50.45

, . FILTER_FLAG_ALLOW_THOUSAND, . , , .

PHP: unformat money. $50.45. NumberFormatter , , 100%, , .

0

All Articles