00 Votes

PHP: Fill up string forward or backward with arbitrary characters to certain length

Tip by Computer Expert | 2012-06-17 at 19:44

In this little tip, I want to introduce a useful PHP function.

Often, we have strings of a certain length and we want to fill up them with characters at their front or their back, so that the strings come to a uniform length. It would be conceivable, for example, to justify names with points and spaces or to fill up shorter numbers with zeros like:

0000123
0012345
0000012

If we would like to produce such a result with an own function, we will need a few lines of code.

Fortunately, PHP provides us with an appropriate function. It is called str_pad() and we can use it like it is shown in the following example:

$str = 'abc';
echo str_pad($str, 5, '.');                // '..abc'
echo str_pad($str, 5, '.', STR_PAD_RIGHT); // '..abc'
echo str_pad($str, 5, '.', STR_PAD_LEFT);  // 'abc..'
echo str_pad($str, 5, '.', STR_PAD_BOTH);  // '.abc.'
echo str_pad($str, 8, '. ');               // '. . .abc'
echo str_pad($str, 8);                     // '     abc'

The function takes a string as the first parameter and the second parameter is a value, how long the string should be.

The third, optional parameter is the character or the set of characters to be used for filling. If you omit this parameter, a blank is used. If the number of characters for filling is not fitting, the filling characters are just cut, so that they come to the right length.

The fourth and last parameter specifies whether the string should be filled right justified (STR_PAD_RIGHT), left justified (STR_PAD_LEFT) or centrally (STR_PAD_BOTH). If you omit this parameter, the function uses a right alignment.

ReplyPositiveNegative

About the Author

AvatarThe author has not added a profile short description yet.
Show Profile

 

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.