Reputation: 1511
I'm trying to convert the following numbers, so that all have the same value of 5460 if there is no comma or dot used at the third last position or 5460,00 if there is a comma or dot.
Here are my test numbers:
5460
5.460
5.460€
5460,00
5460,00€
5460.00
5460.00€
5.460,00
5.460,00€
5,460.00
5,460.00€
I used the following regex with preg_replace:
preg_replace('/[^0-9\,\-]+/','',$number);
The result was the following
5460 -> 5460
5.460 -> 5460
5.460€ -> 5460
5460,00 -> 5460,00
5460,00€ -> 5460,00
5460.00 -> 546000 // wrong
5460.00€ -> 546000 // wrong
5.460,00 -> 5460,00
5.460,00€ -> 5460,00
I don't know how to optimize the regex, so that also the wrong values will be correct replaced like this:
5460.00 -> 546000 // wrong because should be 5460,00
5460.00€ -> 546000 // wrong because should be 5460,00
Test case:
$numbers = array('5460', '5.460', '5.460€', '5460,00', '5460,00€', '5460.00', '5460.00€', '5.460,00', '5.460,00€');
foreach ($numbers as $number)
echo $number." -> ".preg_replace('/[^0-9\,\-]+/','',$number) . "\n";
So I don't know how to check if the last two digits have a dot before, and if yes to replace it with a comma. But only for the last two digits.
Thanks
Upvotes: 0
Views: 737
Reputation: 89584
This does the job, but there's probably a more simple solution:
$numbers = array('5460', '5.460', '5.460€', '5460,00', '5460,00€', '5460.00', '5460.00€', '5.460,00', '5.460,00€');
foreach ($numbers as $k => $number) {
$number = preg_replace('~[.,](?=\d{2}\b)|\p{Sc}~u', '#', $number);
$number = strtr(rtrim($number, '#'), ['#' => ',', '.' => '', ',' => '']);
echo $numbers[$k], ' -> ', $number, PHP_EOL;
}
The pattern matches the currency symbol and the dot or the comma followed by only two digits. They are replaced with a dash.
For example : 5.460,00€ => 5.460#00#
Then the dash is stripped on the right, and with strtr
remaining dashes are translated to commas and commas or dots to empty string at the same time.
Upvotes: 1
Reputation: 42354
Considering how many different ways there are to write currency (even just with Euros), you may struggle using a simple regex to identify the 'true' value people are intending to enter.
You may benefit from something like PHP's money_format() to automatically correct for any possible confusion, by setting the locale with setlocale():
setlocale(LC_MONETARY, 'de_DE');
$numbers = array('5460', '5.460', '5.460€', '5460,00', '5460,00€', '5460.00', '5460.00€', '5.460,00', '5.460,00€');
foreach ($numbers as $number)
echo money_format('%i', $number) . "\n";
This will automatically take any values inputted and convert them to the German equivalent. Keep in mind that you'll also want to strip out the Euro signs!
Hope this helps! :)
Upvotes: 0