Home >Backend Development >PHP Tutorial >Several methods of padding 0s on the left side of numeric strings in PHP, filling strings, and automatically completing them_PHP Tutorial
1. Numbers are supplemented by 0.
If you want to automatically generate a student number, automatically generate a certain number, like this form "d0000009", "d0000027", then you will face a problem, how to fill in the left side with 0 to become like this 8 What about the encoding of digits? I thought of two ways to achieve this function.
Method 1:
First construct a number 10000000, tens of millions, that is, a 1, 7 zeros, and then add the current number (for example, 3), then you will get 10000003, use the string to intercept substr('10000003',1, 7), you get 0000003, and finally splice it with "d" to get the final number d0000003.
The source code is as follows:
Method 2:
Measure the length of the current number (for example, 3) strlen('3')=1, subtract the length of the current number from the total length of the number to be generated, get the number of 0s that need to be filled, and then use a for loop to fill it 0 is enough.
The source code is as follows:
Method 3: Several other methods
2. String filling, auto-complete, auto-complete
When you need to output a string of a certain length, you can use the following two methods to automatically fill and complete PHP strings.
Method 1:
The function of sprintf() is very flexible. In the above format string, "%05s" means outputting a string with a length of 5. If the length is insufficient, the left side is filled with zeros; if it is written as "%5s", then By default, spaces are used for completion; if you want to use other characters for completion, you must add a single quotation mark before the character, that is, a form such as "%'#5s" means completion with a pound sign; finally, if you want completion to occur in On the right side of the string, add a minus sign after the percent sign, "%-05s".
Method 2:
[code]$cd_no = str_pad(++$next_cd_no,8,'#',STR_PAD_LEFT);
str_pad(string,length,pad_string,pad_type): See the manual for specific usage.
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 the side of the padding string.
These two methods conveniently implement the automatic completion function of PHP strings.