Reputation: 323
I am trying to find a piece of regex to remove a currency format.
I have two types of currency values. One is in USD format like 1,000.00 and other is in EUR like 1.000,00. I need to save the value in to db by removing both comma and dot like 1000.00
For example if the user enter the value in USD like 2,222.65, it need to replace to 2222.65,
if the user enter the value in EUR like 2.222,65 it also need to replace to 2222.65,
Upvotes: 1
Views: 2620
Reputation: 4051
This assumes that they all have decimals, but it is the cleanest.
$str = "2,222.65";
$clean = preg_replace('/[^\d]/', '', $str);
$clean = substr($clean, 0,-2) . "." . substr($clean,-2);
Upvotes: 0
Reputation: 786359
Instead of complex regex, use NumberFormatter::parse
available for PHP 5 >= 5.3.0, PECL intl >= 1.0.0
.
// German format
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
$num = "1.234.567,891";
echo $fmt->parse($num)."<br>\n";
// USD format
$fmt = new NumberFormatter( 'en_US', NumberFormatter::DECIMAL );
$num = "9,876,543.012";
echo $fmt->parse($num)."<br>\n";
OUTPUT:
1234567.891
9876543.012
Upvotes: 1
Reputation: 5846
One soultion to match what separator in use, and change it to the one you prefere
<?php
/* split input in 3 parts: integer, separator, decimals */
if(preg_match('#^(?<integer>.*)(?<separator>[\.,])(?<decimals>[0-9]+)$#', $input, $matches))
{
/* clean integer and append decimals with your own separator */
$number = ((int) preg_replace('#[^0-9]+#', '', $matches['integer']) . '.' . $matches['decimals']
}
else
{
$number = (int) preg_replace('#[^0-9]+#', '', $input);
}
?>
Notice: I prefer to have my regexp in # insted of /, as i ofen use / inside my regexp,
if ypu prefer / you can use /[^0-9]+/
and /^(?<integer>.*)(?<separator>[\.,])(?<decimals>[0-9]+)$/
Upvotes: 1