In PHP, you can use the str_pad() function to pad 0 if the string is not enough. This function can use specified characters to fill the string to the specified length. You only need to set the third parameter to "0" and the fourth parameter to "STR_PAD_LEFT" to realize that if the string length is not enough, fill it with 0 in front. Syntax "Syntax "str_pad(string, specified length, "0", STR_PAD_LEFT)".
The operating environment of this tutorial: Windows 7 system, PHP version 8.1 , DELL G3 computer
In php, you can use the str_pad() function to add 0 in front if the string length is not long enough.
str_pad() function can Fill the string to the new length, that is, fill the string to the specified length with the specified characters.
str_pad(string,length,pad_string,pad_type)
Parameter | Description |
---|---|
string | Required. Specifies the string to be padded. |
length | Required. Specifies the length of the new string. If the value is less than the length of the original string, no operation is performed. |
pad_string | Optional. Specifies the string used for padding. Default is blank. |
pad_type | Optional. Specifies the padding string Which side of the string. Possible values:
|
<?php header('content-type:text/html;charset=utf-8'); $str="123456"; echo "原字符串:".$str."<br><br>"; echo "前面用0补位后:".str_pad($str,10,"0",STR_PAD_LEFT)."<br><br>"; ?>
<?php header('content-type:text/html;charset=utf-8'); $str="123456"; echo "原字符串:".$str."<br><br>"; echo "后面用0补位后:".str_pad($str,10,"0")."<br><br>"; echo "首尾用0补位后:".str_pad($str,10,"0",STR_PAD_BOTH)."<br><br>"; ?>
PHP Video Tutorial"
The above is the detailed content of How to add 0 in front of the string if the string length is not long enough in php. For more information, please follow other related articles on the PHP Chinese website!