In PHP, you can use the str_pad() function to pad the string with 0s. This function can fill a string with specified characters to a specified length. You only need to set the third parameter to "0" to fill in the missing length with 0. The syntax is "str_pad(string, specified length, '0', type )"; the parameter "type" specifies the padding direction. The value "STR_PAD_BOTH" is filled on both sides, the value "STR_PAD_LEFT" is filled with the left side, and the value "STR_PAD_RIGHT" is filled with the right side.
The operating environment of this tutorial: Windows 7 system, PHP version 8.1, DELL G3 computer
In PHP, you can use str_pad The () function realizes filling in 0 if the string is missing.
str_pad() function can fill the string to a new length, that is, fill the string to the specified length with the specified characters.
str_pad(string,length,pad_string,pad_type)
Parameters | Description |
---|---|
string | Required . Specifies the string to be filled. |
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. The default is blank. |
pad_type | Optional. Specifies which side of the string to fill. Possible values:
|
You only need to set the third parameter pad_string to "0" to fill in the missing length with 0.
Example:
<?php header('content-type:text/html;charset=utf-8'); $str="123456"; echo "原字符串:".$str."<br><br>"; echo "补位后:".str_pad($str,10,"0")."<br><br>"; echo "补位后:".str_pad($str,10,"0",STR_PAD_BOTH)."<br><br>"; echo "补位后:".str_pad($str,10,"0",STR_PAD_LEFT)."<br><br>"; ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to add 0 if the php string is insufficient. For more information, please follow other related articles on the PHP Chinese website!