douxiajia6309 2017-07-18 21:37
浏览 26
已采纳

通过替换第三个最后位置上的点来转换货币数字与preg_replace

I'm trying to convert the following numbers, so that all have the same value of 5460 if there is no comma or dot used at the third last position or 5460,00 if there is a comma or dot.

Here are my test numbers:

5460
5.460
5.460€
5460,00
5460,00€
5460.00
5460.00€
5.460,00
5.460,00€
5,460.00
5,460.00€

I used the following regex with preg_replace:

preg_replace('/[^0-9\,\-]+/','',$number);

The result was the following

5460 -> 5460
5.460 -> 5460
5.460€ -> 5460
5460,00 -> 5460,00
5460,00€ -> 5460,00
5460.00 -> 546000 // wrong
5460.00€ -> 546000 // wrong
5.460,00 -> 5460,00
5.460,00€ -> 5460,00

I don't know how to optimize the regex, so that also the wrong values will be correct replaced like this:

5460.00 -> 546000 // wrong because should be 5460,00
5460.00€ -> 546000 // wrong because should be 5460,00

Test case:

$numbers = array('5460', '5.460', '5.460€', '5460,00', '5460,00€', '5460.00', '5460.00€', '5.460,00', '5.460,00€');
foreach ($numbers as $number)
    echo $number." -> ".preg_replace('/[^0-9\,\-]+/','',$number) . "
";

So I don't know how to check if the last two digits have a dot before, and if yes to replace it with a comma. But only for the last two digits.

Thanks

  • 写回答

2条回答 默认 最新

  • douzhu3367 2017-07-18 23:46
    关注

    This does the job, but there's probably a more simple solution:

    $numbers = array('5460', '5.460', '5.460€', '5460,00', '5460,00€', '5460.00', '5460.00€', '5.460,00', '5.460,00€');
    foreach ($numbers as $k => $number) {
        $number = preg_replace('~[.,](?=\d{2}\b)|\p{Sc}~u', '#', $number);
        $number = strtr(rtrim($number, '#'), ['#' => ',', '.' => '', ',' => '']);
        echo $numbers[$k], ' -> ', $number, PHP_EOL;
    }
    

    The pattern matches the currency symbol and the dot or the comma followed by only two digits. They are replaced with a dash.

    For example : 5.460,00€ => 5.460#00#

    Then the dash is stripped on the right, and with strtr remaining dashes are translated to commas and commas or dots to empty string at the same time.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 前端echarts坐标轴问题
  • ¥15 CMFCPropertyPage
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题
  • ¥15 谁会P4语言啊,我想请教一下
  • ¥15 这个怎么改成直流激励源给加热电阻提供5a电流呀
  • ¥50 求解vmware的网络模式问题 别拿AI回答
  • ¥24 EFS加密后,在同一台电脑解密出错,证书界面找不到对应指纹的证书,未备份证书,求在原电脑解密的方法,可行即采纳