You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在PHP中使用正则表达式格式化数字?

要实现开头始终保留3位数字,之后按每3位分割(末尾可留1-2位)的格式,你可以用以下两种方式修改代码:

方法一:分步处理

先截取前3位,再对剩余部分用原逻辑添加分隔符:

$input = '12345678911';
if (strlen($input) > 3) {
    $prefix = substr($input, 0, 3);
    $suffix = substr($input, 3);
    $suffix = preg_replace('/(?!^)(?=(?:\d{3})+$)/', '.', $suffix);
    $repl = $prefix . '.' . $suffix;
} else {
    $repl = $input;
}
// 输出结果:123.456.789.11

方法二:用回调函数一次性处理

通过preg_replace_callback合并两步操作:

$input = '12345678911';
$repl = preg_replace_callback(
    '/^(\d{3})(\d+)$/',
    function($matches) {
        return $matches[1] . '.' . preg_replace('/(?!^)(?=(?:\d{3})+$)/', '.', $matches[2]);
    },
    $input
);
// 输出结果:123.456.789.11

效果说明

  • 输入123 → 输出123
  • 输入1234 → 输出123.4
  • 输入1234567 → 输出123.456.7
  • 输入12345678911 → 输出123.456.789.11

内容的提问来源于stack exchange,提问作者Tomas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 07:45:20