在 PHP 中解析时取消货币格式

发布于 2024-12-04 23:00:01 字数 147 浏览 2 评论 0原文

有没有办法获取像这样的字符串的浮点值:75,25 €,而不是parsefloat(str_replace(',', '.', $var))?

我希望这取决于当前的站点语言,有时逗号可以用点代替。

Is there a way to get the float value of a string like this: 75,25 €, other than parsefloat(str_replace(',', '.', $var))?

I want this to be dependent on the current site language, and sometimes the comma could be replaced by dot.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

你是我的挚爱i 2024-12-11 23:00:01

这是一个稍微复杂/缓慢的解决方案,但适用于所有区域设置。 @rlenom 的解决方案仅适用于点作为小数分隔符,而某些语言环境(例如西班牙语)使用逗号作为小数分隔符。

<?php

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

测试:

['1,10 USD', 1.10],
['1 000 000.00', 1000000.0],
['$1 000 000.21', 1000000.21],
['£1.10', 1.10],
['$123 456 789', 123456789.0],
['$123,456,789.12', 123456789.12],
['$123 456 789,12', 123456789.12],
['1.10', 1.1],
[',,,,.10', .1],
['1.000', 1000.0],
['1,000', 1000.0]

注意事项:
如果小数部分超过两位数则失败。

这是该库的一个实现:
https://github.com/mcuadros/currency-detector

This is a bit more complex/ slow solution, but works with all locales. @rlenom's solution work only with dots as decimal separator, and some locales, like Spanish, use the comma as decimal separator.

<?php

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

Tests:

['1,10 USD', 1.10],
['1 000 000.00', 1000000.0],
['$1 000 000.21', 1000000.21],
['£1.10', 1.10],
['$123 456 789', 123456789.0],
['$123,456,789.12', 123456789.12],
['$123 456 789,12', 123456789.12],
['1.10', 1.1],
[',,,,.10', .1],
['1.000', 1000.0],
['1,000', 1000.0]

Caveats:
Fails if the decimal part have more than two digits.

This is an implementation from this library:
https://github.com/mcuadros/currency-detector

仅冇旳回忆 2024-12-11 23:00:01

您可以使用

手册中的示例:

$formatter = new NumberFormatter('de_DE', NumberFormatter::CURRENCY);
var_dump($formatter->parseCurrency("75,25 €", $curr));

给出: float(75.25)

请注意 国际扩展 默认情况下不启用。请参阅安装说明

You can use

Example from Manual:

$formatter = new NumberFormatter('de_DE', NumberFormatter::CURRENCY);
var_dump($formatter->parseCurrency("75,25 €", $curr));

gives: float(75.25)

Note that the intl extension is not enabled by default. Please refer to the Installation Instructions.

淡淡绿茶香 2024-12-11 23:00:01

使用 ereg_replace

$string = "$100,000";
$int = ereg_replace("[^0-9]", "", $string); 
echo $int;

输出

1000000

function toInt($str)
{
    return (int)preg_replace("/\..+$/i", "", preg_replace("/[^0-9\.]/i", "", $str));
}

更新


<?php
$string = array("$1,000,000.00","$1 000 000.00","1,000 000.00","$123","$123 456 789","0.15¢");
foreach($string as $s) {
    echo $s . " = " . toInt($s) . "\n"; 
}
function toInt($str)
{
    return preg_replace("/([^0-9\\.])/i", "", $str);
}
?>

输出

$1,000,000.00 = 1000000.00
$1 000 000.00 = 1000000.00
1,000 000.00 = 1000000.00
$123 = 123
$123 456 789 = 123456789
0.15¢ = 0.15

如果将其转换为整数

<?php
$string = array("$1,000,000.00","$1 000 000.00","1,000 000.00","$123","$123 456 789","0.15¢");
foreach($string as $s) {
    echo $s . " = " . _toInt($s) . "\n";    
}
function _toInt($str)
{
    return (int)preg_replace("/([^0-9\\.])/i", "", $str);
}
?>

输出

$1,000,000.00 = 1000000
$1 000 000.00 = 1000000
1,000 000.00 = 1000000
$123 = 123
$123 456 789 = 123456789
0.15¢ = 0

那么你就得到了它。单行,一次替换。你可以走了。

use ereg_replace

$string = "$100,000";
$int = ereg_replace("[^0-9]", "", $string); 
echo $int;

outputs

1000000

function toInt($str)
{
    return (int)preg_replace("/\..+$/i", "", preg_replace("/[^0-9\.]/i", "", $str));
}

Update


<?php
$string = array("$1,000,000.00","$1 000 000.00","1,000 000.00","$123","$123 456 789","0.15¢");
foreach($string as $s) {
    echo $s . " = " . toInt($s) . "\n"; 
}
function toInt($str)
{
    return preg_replace("/([^0-9\\.])/i", "", $str);
}
?>

Outputs

$1,000,000.00 = 1000000.00
$1 000 000.00 = 1000000.00
1,000 000.00 = 1000000.00
$123 = 123
$123 456 789 = 123456789
0.15¢ = 0.15

and if you cast it as an integer

<?php
$string = array("$1,000,000.00","$1 000 000.00","1,000 000.00","$123","$123 456 789","0.15¢");
foreach($string as $s) {
    echo $s . " = " . _toInt($s) . "\n";    
}
function _toInt($str)
{
    return (int)preg_replace("/([^0-9\\.])/i", "", $str);
}
?>

outputs

$1,000,000.00 = 1000000
$1 000 000.00 = 1000000
1,000 000.00 = 1000000
$123 = 123
$123 456 789 = 123456789
0.15¢ = 0

So there you have it. single line, one replace. you're good to go.

剪不断理还乱 2024-12-11 23:00:01

您需要从字符串中删除货币符号。 PHP 的 intval 在找到的第一个非数字字符处停止。

$int = intval(preg_replace('/[^\d\.]/', '', '$100')); // 100

不过,如果您的值类似于 $100.25,您可能需要使用 floatval 来代替。

$float = floatval(preg_replace('/[^\d\.]/', '', '$100.25')); // 100.25

You're gonna need to remove the currency symbol from the string. PHP's intval stops at the 1st non-numeric character it finds.

$int = intval(preg_replace('/[^\d\.]/', '', '$100')); // 100

Though if you have a value like $100.25, you might wanna use floatval instead.

$float = floatval(preg_replace('/[^\d\.]/', '', '$100.25')); // 100.25
把时间冻结 2024-12-11 23:00:01

PHP 有 intval这里是文档),这是(据我所知告诉)与 JavaScript 的 parseInt 完全相同。

然而,就其价值而言,我认为这两个功能都无法帮助您完成您想要做的事情。因为第一个字符是非数字,所以两者都吓坏了(PHP 会给你 0,JS 会给你 NaN)。因此,无论哪种语言,您都必须进行一些字符串/正则表达式解析。

PHP has intval (here are the docs), which is (as far as I can tell) exactly the same as JavaScript's parseInt.

However, for what's worth, I don't think either function will help you with what you're trying to do. Because the first character is non-numeric, both freak out (PHP will give you 0, JS will give you NaN). So in either language, you're going to have to do some string/regex parsing.

情魔剑神 2024-12-11 23:00:01

我是新手,所以下面的方法可能有一个明显的(对其他人,而不是我)缺点,但我想无论如何都会分享它。我有兴趣知道它比使用 preg_replace 更快还是更慢,但没有进行任何速度测试。

$badChars = array("$", ",", "(", ")");
$dirtyString = "($3,895.23)";
$cleanString = str_ireplace($badChars, "", $dirtyString);
echo "$dirtyString becomes $cleanString<p>";

$dirtyString 可以是一个数组,所以:

$badChars = array("$", ",", "(", ")");
$dirtyStrings = array("($3,895.23)", "1,067.04", "$5683.22", "$9834.48");
$cleanStrings = str_ireplace($badChars, "", $dirtyStrings);

echo var_dump($cleanStrings);

I'm an newbie, so there's probably an obvious (to others, not me) downside to the approach below, but thought I would share it anyway. I'd be interested to know whether it's faster or slower than using preg_replace, but didn't do any speed testing.

$badChars = array("$", ",", "(", ")");
$dirtyString = "($3,895.23)";
$cleanString = str_ireplace($badChars, "", $dirtyString);
echo "$dirtyString becomes $cleanString<p>";

$dirtyString can be an array, so:

$badChars = array("$", ",", "(", ")");
$dirtyStrings = array("($3,895.23)", "1,067.04", "$5683.22", "$9834.48");
$cleanStrings = str_ireplace($badChars, "", $dirtyStrings);

echo var_dump($cleanStrings);
恰似旧人归 2024-12-11 23:00:01

铸造是你的朋友:

$int = (int) $string;

更新基于op

尝试这样的事情:

<?php

function extract_numbers($string)
{
    return preg_replace("/[^0-9]/", '', $string);
}

echo extract_numbers('$100');

?>

演示:http://codepad.org/QyrfS7WE

Casting is your friend:

$int = (int) $string;

Update based on op:

Try something like this:

<?php

function extract_numbers($string)
{
    return preg_replace("/[^0-9]/", '', $string);
}

echo extract_numbers('$100');

?>

Demo: http://codepad.org/QyrfS7WE

混吃等死 2024-12-11 23:00:01

我遇到了类似的问题,我没有收到货币符号,只收到字符串(即:1,234,567.89 或 1.234.567,89)。

这帮助我将这两种情况标准化为浮点数:

$val = str_replace(",", ".", $formatted);
$val = preg_replace("/[\,\.](\d{3})/", "$1", $val);

但戈登的答案更加清晰。

I had a similar problem where I didn't receive the currency symbol, just the strings (ie: 1,234,567.89 or 1.234.567,89).

This helped me normalize both cases into floats:

$val = str_replace(",", ".", $formatted);
$val = preg_replace("/[\,\.](\d{3})/", "$1", $val);

But Gordon's answer is much cleaner.

满地尘埃落定 2024-12-11 23:00:01

filter_var 比正则表达式解决方案快得多:

   $m = "$1,345.00";
   $m = filter_var($m, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);

   echo $m;

1345.00

让它变得更复杂是没有意义的。

filter_var is much faster than regex solutions:

   $m = "$1,345.00";
   $m = filter_var($m, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);

   echo $m;

1345.00

No sense making it more complicated than it is.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文