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
<?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
)
preg_replace('/.*?(\d+)(?:[.,](\d+))?.*/', '\1.\2', $string);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With