How to Parse Currency Strings in PHP with Multiple Locales?

Barbara Streisand
Release: 2024-11-13 03:13:02
Original
896 people have browsed it

How to Parse Currency Strings in PHP with Multiple Locales?

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);
}
Copy after login

Explanation

  • preg_replace() removes non-numeric characters and isolates the decimal separator.
  • The count of separators is determined to remove them one at a time until only the decimal separator remains.
  • The string is then cleaned up to remove thousand separators, and finally, a float value with the correct decimal separator is returned.

Caveats

  • This method fails if the decimal part exceeds two digits.
  • If dealing with such scenarios, consider using a library like currency-detector (https://github.com/mcuadros/currency-detector) for more comprehensive handling.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template