Php:将前 6 个字符分成 3 个字符,用短划线分隔


Php: Group the first 6 characters into 3 divided by a dash

我想格式化一个数字,该数字采用前 6 位数字并将它们分组为 3 个,用破折号"432-243-23243"分隔。我怎样才能允许最后的数字有任何长度。

preg_replace("/^('d{3})('d{3})('d{1,13})$/", "$1-$2-$3", $number);

我尝试使用 substr implode("-", str_split($num, 3));但我得到了这个结果

000-000-000-0

我希望数字像"000-000-000000"

你的代码运行良好:

<?php
$number = "123456789123";
$num = preg_replace("/^('d{3})('d{3})('d+)$/", "$1-$2-$3", $number);
echo $num; // 123-456-789123
?>

我总是更喜欢字符串函数而不是 REGEX,如果它可以完成工作......

$str = '00000000000000000';
$repl = implode('-', str_split(substr($str, 0, 6), 3)) . '-';
echo substr_replace($str, $repl, 0, 6);
//  result: 000-000-00000000000

或者:

$repl = str_pad(substr($str, 3, 3), 5, '-', STR_PAD_BOTH);
echo substr_replace($str, $repl, 3, 5);

或者:

echo substr_replace($str, $str[0].$str[1].$str[2].'-'.$str[3].$str[4].$str[5].'-', 0, 6);
您可以使用

preg_replace limit 参数(如果您已经知道字符串仅包含数字和至少七个):

$str = preg_replace('~...'K~', '-', $str, 2);