Parsing Currency Strings in PHP
When parsing currency strings in PHP, it can be challenging to handle varying decimal separators depending on the current locale. While using str_replace() to convert commas to dots can work for some cases, it relies on the assumption that the decimal separator is always a dot.
A More Robust Solution
To address this limitation and cater to multiple locales, a more complex but versatile solution is to employ regular expressions (regex). Here's how to do it:
public function getAmount($money) { $cleanString = preg_replace('/([^0-9\.,])/i', '', $money); $onlyNumbersString = preg_replace('/([^0-9])/i', '', $money); $separatorsCountToBeErased = strlen($cleanString) - strlen($onlyNumbersString) - 1; $stringWithCommaOrDot = preg_replace('/([,\.])/', '', $cleanString, $separatorsCountToBeErased); $removedThousandSeparator = preg_replace('/(\.|,)(?=[0-9]{3,}$)/', '', $stringWithCommaOrDot); return (float) str_replace(',', '.', $removedThousandSeparator); }
Explanation
Caveats
The above is the detailed content of How to Parse Currency Strings in PHP with Multiple Locales?. For more information, please follow other related articles on the PHP Chinese website!