Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What a quick way to clean up a monetary string [duplicate]

Tags:

regex

php

Possible Duplicate:
PHP: unformat money

How to get rid of everything that is not a number or dot, replacing , with . using a light regex?

Examples:

$50.45     = 50.45
USD 50.45  = 50.45
50,45      = 50.45
USD$ 50.45 = 50.45
like image 469
CodeOverload Avatar asked Jul 12 '11 09:07

CodeOverload


3 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);
?>

Output:

Array
(
    [0] => 50.45
    [1] => 50.45
    [2] => 50.45
    [3] => 50.45
)
like image 163
Shef Avatar answered Nov 18 '22 19:11

Shef


preg_replace('/.*?(\d+)(?:[.,](\d+))?.*/', '\1.\2', $string);
like image 38
Artefacto Avatar answered Nov 18 '22 19:11

Artefacto


The solution I came up with that works with your examples was:

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

Assuming comma only ever appears when it should be a decimal point, as opposed to being a thousands separator. It replaces those with a decimal place, and then removes all non numeric/decimal characters from the remaining string altogether.

Test 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/>";    
}

Output:

GIVEN: $50.45 -> CLEAN: 50.45

GIVEN: USD 50.45 -> CLEAN: 50.45

GIVEN: 50,45 -> CLEAN: 50.45

GIVEN: USD$ 50.45 -> CLEAN: 50.45

like image 1
Codecraft Avatar answered Nov 18 '22 20:11

Codecraft