如何在php中添加零到字符串

时间:2016-07-18 13:49:29

标签: php string format zero

我有字符串:23-65, 123-45, 2-5435, 345-4 我想为它们添加零,所以它们看起来都像###-#### (three digits dash four digits): 023-0065, 123-0045, 002-5435, 345-0004 我怎么能在PHP中做到这一点? 谢谢!

2 个答案:

答案 0 :(得分:1)

您需要使用

拆分它们
$parts = explode('-', $number);`

然后使用str_pad函数:

$parts[0] = str_pad($parts[0], 3, "0");
$parts[1] = str_pad($parts[0], 4, "0");

再将它们连接起来

$number = implode('-', $parts);

或者,您可以使用vsprintf填充它们:

$number = vsprintf('%03d-%04d', $parts);

答案 1 :(得分:1)

尝试:

$str = "23-65, 123-45, 2-5435, 345-4";
$numArray = explode(",",$str);
$str_new = "";

foreach($numArray as $nums) {
  $nums = explode("-",$nums);
  $num1 = str_pad($nums[0], 3, '0', STR_PAD_LEFT);
  $num2 = str_pad($nums[1], 4, '0', STR_PAD_LEFT);
  $str_new .= $num1."-".$num2.",";
}
$str_new = rtrim($str_new,",");

输出:

023-0065, 123-0045,0 2-5435, 345-0004