Changes

Jump to: navigation, search

Working with Strings and Text in PHP

2,173 bytes added, 13:58, 4 June 2007
PHP fprintf formatting specifiers
</table>
before Before we look at the fomratting formatting options for we first need to see some of the above rules in action. Let's begin by embedding a string variable into a PHP fprintf printf function call:
<pre>
$myString = "Green";
$formatted = fprintf printf ("My favorite color is %s.", $myString);
echo $formatted;
<tt>My favorite color is Green.</tt>
 
We can now consider creating an printf statements which combines a number of differnet formatting rules:
 
<pre>
<?php
 
$myString = "Green";
 
$myNumber = 10;
 
$formatted = printf ("My favorite color is %s and my lucky number is %d.", $myString, $myNumber);
 
echo $formatted;
?>
 
</pre>
 
In the above example the %s will be replaced by the value of $myString and the %d will be replaced by the decimal value of $myNumber to create a string which reads:
 
<tt>My favorite color is Green and my lucky number is 10.</tt>
 
Suppose we wanted to display our lucky number as a hexadicamal value. All we would need to do is replace the %d with a %x:
 
<pre>
$formatted = fprintf ("My favorite color is %s and my lucky number is %x.", $myString);
</pre>
 
Finally we need to look at the formatting options which may be specified after the '%' caharacter.
 
* '''+''' - Forces both + or - in front of numbers. By default, only negative numbers display their sign.
 
* ''''n'''' - Specifies what to use as padding. Default is space. Must be used together with the width specifier. Example: %'x20s (this uses "x" as padding)
* - (Left-justifies the variable value)
* [0-9] (Specifies the minimum width held of to the variable value)
* .[0-9] (Specifies the number of decimal digits or maximum string length)
 
 
The first option can be a '+' or a '-' and dictates whether the number shoudl display its sign. For example ''%+d'' would force the number to be displayed with a + sign if it was positive.
 
The second option specifies the padding character enclosed in single quotes. The default is a space character. Used in conjuction with the witch specifier.
 
The next value specified whether the output should be left or right justified. A minus (-) sign forces left justification. The default is right justification.
 
The width value specificies the minumum width the value should occupy in the string. Excess space is filled with spaces unless the above padding character is specified.
 
The final value represents the level of precision (i.e places after the decimal point to which the value should be displayed.
 
As always ome examples will hopefully help to clarify these options:

Navigation menu