A tutorial on the methods of filling 0 on the left side of PHP numeric string, string filling and automatic completion
This article mainly explains "PHP numeric string left filling 0, string filling and automatic completion method tutorial", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Next let the editor to take you to learn the "PHP numeric string left filling 0, string filling and automatic completion method tutorial"!
First, the number adds up to 0.
If you want to automatically generate a student number, automatically generate a certain number, such as this form "d0000009", "d0000027", then you will be faced with a problem, how to make up the left side with 0 to such an 8-digit code? I thought of two ways to do this.
Method 1:
First construct a number 10000000, 10 million, that is, a 1P 7 zeros, and then add the current number (for example, 3), then you get 10000003. After intercepting substr with a string ('10000003 last minute 7), you get 0000003. Finally, after splicing with "d", you get the final number d0000003.
The source code is as follows
The copy code is as follows:
Method 2:
Measure the length of the current number (for example, 3) strlen ('3') = 1, subtract the current number length from the total length of the number to be generated, get the number of zeros that need to be filled, and then fill 0 with a for loop.
The source code is as follows
The copy code is as follows:
Method 3: other methods
The copy code is as follows:
/ * it will appear at this time: 001
If you want to increase the number of digits, you can increase 1000, and then increase 3.
For example: if I want to make up "4 zeros", line 03 will be like this. , /
The copy code is as follows:
/ * in fact, if you want to display a total of several digits, add how many zeros after $sourceNumber+1, and the last number will be directly changed to show several digits. , /
The copy code is as follows:
/ * string str_pad (string $input, int $pad_length [, string $pad_string [, int $pad_type]]) * /
/ * complete the length of the string. Make up with pad_string. The default patch is on the right, and if STR_PAD_LEFT is added to the left, both sides of the STR_PAD_BOTH will be filled together. The next time you use str_pad, it is built-in after all, and it must be faster than the custom one. , /
The copy code is as follows:
/ *
I don't think the above method is very good. Tell me about a method I wrote. The method function is as follows, so that when you want the result 0 01, the method: dispRepair ('1 minute copy 3 minute 0')
Function: complement function
Str: original string
Type: type. 0 is post-supplement, 1 is pre-supplement.
Len: new string length
Msg: filling characters
, /
Function dispRepair ($str,$len,$msg,$type='1') {
$length = $len-strlen ($str)
If ($length