Ben*_*Ben 199 php string numbers zero
PHP - 是否有一种快速,即时的方法来测试单个字符串,然后预先设置一个前导零?
例:
$year = 11;
$month = 4;
$stamp = $year.add_single_zero_if_needed($month); // Imaginary function
echo $stamp; // 1104
Run Code Online (Sandbox Code Playgroud)
Kir*_*ard 447
您可以使用sprintf:http://php.net/manual/en/function.sprintf.php
<?php
$num = 4;
$num_padded = sprintf("%02d", $num);
echo $num_padded; // returns 04
?>
Run Code Online (Sandbox Code Playgroud)
如果它小于所需的字符数,它只会添加零.
编辑:正如@FelipeAls所指出的:
使用数字时,您应该使用%d(而不是%s),尤其是在有负数的情况下.如果您只使用正数,则任一选项都可以正常工作.
例如:
sprintf("%04s", 10);返回0010
sprintf("%04s", -10);返回0-10
在哪里:
sprintf("%04d", 10);返回0010
sprintf("%04d", -10);返回-010
Gau*_*rav 177
您可以使用str_pad添加0
str_pad($month, 2, '0', STR_PAD_LEFT);
Run Code Online (Sandbox Code Playgroud)
string str_pad ( string $input , int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] )
dec*_*eze 17
字符串格式化的通用工具,sprintf:
$stamp = sprintf('%s%02s', $year, $month);
Run Code Online (Sandbox Code Playgroud)
http://php.net/manual/en/function.sprintf.php