Page 127 - Beginning PHP 5.3
P. 127
Chapter 5: Strings
Here ’ s a list of case - insensitive string functions:
F unction C ase - Insensitive E quivalent
strstr() stristr()
strpos() stripos()
strrpos() strripos()
str_replace() str_ireplace()
Formatting Strings
Often, a script ’ s internal representation of a string can look fairly ugly or unreadable to a person using
the script. For example, “ $143,834.12 ” is much easier to understand than “ 143834.12 ” . Fortunately, PHP
gives you a number of functions that you can use to format strings in ways that are more human -
friendly. In this section you explore some of the more common string formatting functions in PHP.
General - Purpose Formatting with printf() and sprintf()
printf() — and its close cousin, sprintf() — are very powerful functions that you can use to format
strings in all sorts of different ways. printf() takes a string argument called a format string , usually followed
by one or more additional arguments containing the string or strings to format. It then outputs the result.
The format string contains ordinary text intermingled with one or more conversion specifications . Each
conversion specification requires an additional argument to be passed to printf() , and it formats that
argument as required and inserts it into the format string. The resulting formatted string is then
displayed. Conversion specifications always start with a percent ( % ) symbol.
This probably sounds a little overwhelming at first glance, so here ’ s a simple example to illustrate
the point:
// Displays “Pi rounded to a whole number is: 3”
printf( “Pi rounded to a whole number is: %d”, M_PI );
In this example, “Pi rounded to a whole number is: %d” is the format string, and the “%d” within
the string is a conversion specification. In this case, the conversion specification tells printf() to read
an additional argument and insert it, formatted as a whole decimal number, into the format string. The
additional argument is the PHP constant M_PI , which represents an approximation of pi to a number of
decimal places (14 by default). So the net result of the function call is to print the format string with the
“%d” replaced by the value of pi rounded to a whole number.
Here ’ s another example that uses multiple conversion specifications:
// Displays “2 times 3 is 6.”
printf( “%d times %d is %d.”, 2, 3, 2*3 );
This code displays three decimal numbers within the output string: 2 , 3 , and the result of the expression 2*3 .
89
9/21/09 8:53:45 AM
c05.indd 89
c05.indd 89 9/21/09 8:53:45 AM