Home  >  Article  >  Backend Development  >  How to Parse Unformatted Monetary Values in PHP?

How to Parse Unformatted Monetary Values in PHP?

Barbara Streisand
Barbara StreisandOriginal
2024-11-12 22:27:01367browse

How to Parse Unformatted Monetary Values in PHP?

Parsing Unformatted Monetary Values in PHP

When attempting to parse monetary values represented as strings, such as "75,25 €," into their numeric equivalents, reliance on using only the parsefloat() method may not always suffice. To address this limitation and ensure flexibility across different locales and separator formats, a more intricate solution is required.

This solution leverages regular expressions to extract numerical values considering various possible separators and formats used in monetary amounts. Given an input string, unnecessary characters are first removed using preg_replace(). Subsequent regex operations identify and remove separators and thousand separators, resulting in a numerical string.

Finally, the cleaned string is subjected to a standard str_replace() operation to unify the decimal separator as a period before casting to a float using (float). This comprehensive approach handles both dot and comma as decimal separators, ensuring accurate parsing regardless of the locale.

Here's an example to illustrate the process:

<?php

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);
}

With this approach, you can confidently parse unformatted monetary strings, obtaining reliable numeric values regardless of language and formatting conventions.

The above is the detailed content of How to Parse Unformatted Monetary Values in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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