Page 134 - Beginning PHP 5.3
P. 134
Part II: Learning the Language
Padding Strings with str_ pad()
You ’ ve already seen how you can use printf() to add padding to the beginning or end of a string.
However, PHP features a dedicated function, str_pad() , that is both more flexible than the printf()
approach and easier to work with.
To use str_pad() , pass the string to be padded, and the desired width of the final string. The function
returns the string padded on the right using space characters (by default):
echo ‘ < pre > ”’;
echo str_pad( “Hello, world!”, 20 ); // Displays “Hello, world! “
echo ‘” < /pre > ’;
To pad using characters other than space, pass a string to use as an optional third argument. Note that
this can be either a single character or a string of characters; in the latter case, the string is repeated as
needed to pad out the input string:
// Displays “Hello, world!*******”
echo str_pad( “Hello, world!”, 20, “*” ) . “\n”;
// Displays “Hello, world!1231231”
echo str_pad( “Hello, world!”, 20, “123” ) . “\n”;
You can also make str_pad() add padding to the left of the string, or to both the left and the right
of the string. To do this, pass an optional fourth argument comprising one of the following built - in
constants:
❑ STR_PAD_RIGHT to pad the string on the right (the default setting), left - aligning the string
❑ STR_PAD_LEFT to pad the string on the left, right - aligning the string
❑ STR_PAD_BOTH to pad the string on both the left and the right, centering the result as much
as possible
The following example adds padding to both the left and right of a string:
// Displays “***Hello, world!****”
echo str_pad( “Hello, world!”, 20, “*”, STR_PAD_BOTH ) . “\n”;
Wrapping Lines of Text with wordwrap()
Sometimes you need to display a large amount of text to a user, such as in a Web page or in an email
message. If your script receives the text as one long line — this might occur as a result of user input, or
due to the way text is formatted in a particular database table — then you might want to break the text
into individual lines to make it easier to read.
PHP ’ s wordwrap() function takes a single - line string of text and splits it into several lines using newline
( “\n” ) characters, wrapping the lines at the ends of words to avoid splitting words. To use it, pass the
string to wrap, and the function returns the wrapped string:
96
9/21/09 8:53:48 AM
c05.indd 96 9/21/09 8:53:48 AM
c05.indd 96