如何在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
相关产品推荐
相关产品推荐

