Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

Name

str_pad()

Synopsis

    string str_pad ( string input, int length [, string padding [, int type]] )

The str_pad() function makes a given string (parameter one) larger by X number of characters (parameter two) by adding on spaces. For example:

    $string = "Goodbye, Perl!";
    $newstring = str_pad($string, 2);

That code would leave " Goodbye, Perl! " in $newstring, which is the same string from $string, except with a space on either side, equalling the two we passed in as parameter two.

There is an optional third parameter to str_pad() that lets you set the padding character to use, so:

    $string = "Goodbye, Perl!";
    $newstring = str_pad($string, 10, 'a');

That would put "aaaaaGoodbye, Perl!aaaaa" into $newstring.

We can extend the function even more by using its optional fourth parameter, which allows us to specify which side we want the padding added to. The fourth parameter is specified as a constant, and you either use STR_PAD_LEFT, STR_PAD_RIGHT, or STR_PAD_BOTH:

    $string = "Goodbye, Perl!";
    $a = str_pad($string, 10, '-', STR_PAD_LEFT);
    // $a is "----------Goodbye, Perl!"

    $b = str_pad($string, 10, '-', STR_PAD_RIGHT);
    // $b is "Goodbye, Perl!----------",

    $c = str_pad($string, 10, '-', STR_PAD_BOTH);
    // $c is "-----Goodbye, Perl!-----"

Note that HTML only allows a maximum of one space at any time. If you want to pad more, you will need to use   the HTML code for a non-breaking space.

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page