【问题标题】:how to clean/sanitize a number with different international formats in PHP?如何在 PHP 中清理/清理具有不同国际格式的数字?
【发布时间】:2019-09-15 09:25:06
【问题描述】:

我在 PHP 中有不同的字符串来表示数字。我正在寻找将它们转换为 MYSQL 兼容数字('4209.99')的函数,无论它们的国际格式如何。

    $test_number= "$4,209.99";
    $test_number= "$4209.99";
    $test_number= "$4209,99";
    $test_number= "4209,99";
    $test_number= "4209.99"; // the right format

【问题讨论】:

标签: php format


【解决方案1】:

假设你总是有 2 个十进制数, 您可以删除所有非数字并除以 100。

$nums = [
    "4209",
    "4209 EUR",
    "$4,209.99",
    "$4209.99",
    "$4209,99",
    "4209,99",
    "4209.99",
    "4209.00",
    "4209,00",
];

foreach($nums as $num) {
    if(preg_match('/([\.\,]*)(\d{2})(\D*)$/', $num, $matches))
    {
        $num = preg_replace('/\D/', '', $num);
        if($matches[1]) $num /= 100;
    }
    echo $num, PHP_EOL;
}

4209

4209

4209.99

4209.99

4209.99

4209.99

4209.99

4209

4209

更新 现在它会处理更多的测试用例,并且只有在有分隔符的情况下才会除以 100。

【讨论】:

  • 好答案,但你问得对,可能有没有小数的 '4209' 可以变成 '42.09'....
  • @RenaudDUGERT 更新答案以通过更多测试
  • 恭喜!完美答案马库斯。
猜你喜欢
  • 2022-12-21
  • 2019-12-07
  • 2016-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-07
  • 2011-08-17
  • 1970-01-01
相关资源
最近更新 更多