Padding 0 on both sides of the PHP string

Source: Internet
Author: User

Str_pad
As the name implies, this function is for a string that can fill any other string with the specified string.

For example: Str_pad (with a filled string, filling the length, filling the string, filling the position)

The length of the fill must be a positive integer, the fill position has three options,
Left: Str_pad_left,
Right: Str_pad_right,
Ends: Str_pad_both

For example:
Echo Str_pad (1, 8, "0″,str_pad_left");
Results: 00000001

Echo Str_pad (1, 8, "0″,str_pad_right");
Results: 10000000

Echo Str_pad (1, 8, "0″,str_pad_both");
Results: 00010000

One of the notable details in the above example is that if the number of digits filled is odd, such as example three fills 7 0, the right priority.

Another way to see Zero is sprintf

This function learned C is very familiar with it, hehe ...

But I do not say so much, because it is too flexible to use, so that I basically do not use, but on the left 0 (or 0 after the decimal point) is very convenient to use.

First look at the left 0
Echo sprintf ("%05d", 1);
First say the meaning of%05d, with a 5-digit number to format the parameters behind, if less than 5 0

Operation result is 00005

Look at the decimal point after 0

Echo sprintf ("%01.3f", 1);

%01.3f means that a minimum of three digits after a decimal point is less than three 0, at least one digit before the decimal point, and a floating-point number that is less than a zero complement is formatted with the parameters behind it.

The operation result is: 1.000

Padding 0 on both sides of the PHP string

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.