Changes

Working with Strings and Text in PHP

7 bytes added, 14:20, 4 June 2007
Printing Formatting Strings in PHP
The ''String'' represents the string that is to displayed and contains the formatting specifiers. The ''variables'' specify the variables that are to be substituted inplace of the respective formatting rules.
=== PHP fprintf printf formatting specifiers ===
The formatting specifiers begin with a '%' character following by a latter letter to indicate the type of variable to be displayed. For example , a string is represented by ''%s''. Optional rules can be placed between the '%' and the ''type'' letter to control formatting.
The following table lists the variable types and the corresponding letter to use when constructing the formatting rule:
<tt>My favorite color is Green.</tt>
We can now consider creating an printf statements which combines combine a number of differnet different formatting rules:
<pre>
<tt>My favorite color is Green and my lucky number is c.</tt>
Finally we need to look at the formatting options which may be specified after the '%' caharactercharacter.
* '''+''' - Forces both + or - in front of numbers. By default, only negative numbers display their signpolarity.
* ''''n''' - Specifies what to use as padding (represented by ''n''). Used in conjunction with the width specifier and defaults to space. Eg: %'_20s specified that '_' should be used as padding.
* '''-''' Left-justifies the value
* [0-9] Specifies the minimum width to be used by the variable - use din used in conjuction with the padding character
* .[0-9] Specifies the number of decimal digits or maximum string length
As always , some examples will hopefully help to clarify these options:
To limit a floating point number to 2 decimal places: