PHP numeric left-side auto-fill 0

Source: Internet
Author: User

Copy codeThe Code is as follows:
<? Php
$ SourceNumber = "1 ";
$ NewNumber = substr (strval ($ sourceNumber + 1000), 1, 3 );
Echo "$ newNumber ";
?>

At this time, the following error occurs: 001.
If you want to increase the number of digits, you can increase the number by 1000, and then increase the number by 3.
For example, if I want to add "4 0" 03rd rows, it will become like this.
Copy codeThe Code is as follows:
<? Php
$ NewNumber = substr (strval ($ sourceNumber + 100000 );
?>

In fact, to display a few digits in total, add the number of zeros after $ sourceNumber + 1, and change the last number to the number of digits.

Better method:
String str_pad (string $ input, int $ pad_length [, string $ pad_string [, int $ pad_type])

Copy codeThe Code is as follows:
<? Php
$ Input = "Alien ";
Echo str_pad ($ input, 10 );
// Produces "Alien"
Echo str_pad ($ input, 10, "-=", STR_PAD_LEFT );
// Produces "-=-Alien"
Echo str_pad ($ input, 10, "_", STR_PAD_BOTH );
// Produces "_ Alien ___"
Echo str_pad ($ input, 6 ,"___");
// Produces "Alien _"
?>


Fill in the length of the string. Pad it with pad_string. It is filled on the right by default. If STR_PAD_LEFT is filled on the left, STR_PAD_BOTH is supplemented on both sides.
The next time we use str_pad, it is built-in and certainly faster than custom.
/*
I think the above method is not very good. Let's introduce a method I wrote. The method function is as follows, so that when you want the result 001, the method is dispRepair ('1', 3, '0 ')
Function: complement function
Str: original string
Type: type. 0 indicates post-completion, and 1 indicates pre-completion.
Len: New String Length
Msg: Fill in characters
*/
Copy codeThe Code is as follows:
Function dispRepair ($ str, $ len, $ msg, $ type = '1 '){
$ Length = $ len-strlen ($ str );
If ($ length <1) return $ str;
If ($ type = 1 ){
$ Str = str_repeat ($ msg, $ length). $ str;
} Else {
$ Str. = str_repeat ($ msg, $ length );
}
Return $ str;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.