When writing PHP code, sometimes use the sprintf () function, then it is how to use it?
Learning Source:
Http://www.w3school.com.cn/php/func_string_sprintf.asp
My application in my project:
Used to put a few long select fields
So we write the SQL statements can be separate writing, separate look, very intuitive and convenient
Instance
Replace the percent sign (%) with a variable that is passed as a parameter:
<?php$number = 2; $str = "Shanghai"; $txt = sprintf ("There is%u million cars in%s.", $number, $STR); Echo $txt; >
Running an instance
Definition and usage
The sprintf () function writes the formatted string to the variable.
The arg1,arg2,+ + parameters are inserted into the percent sign (%) symbol in the main string. This function is executed step-by. At the first% symbol, insert arg1, insert arg2at the second% symbol, and so on.
Note: If the% symbol is more than the arg parameter, you must use a placeholder. The placeholder is located after the% symbol and consists of a number and a "\$". See Example 2.
Tip: Related functions: printf (), vprintf (), vsprintf (), fprintf (), and vfprintf ()
- fprintf ()
- printf ()
- vfprintf ()
- vprintf ()
- vsprintf ()
Grammar
sprintf (format,arg1,arg2,arg++)
Parameters |
Description |
format |
Required. Specifies the string and how to format the variable. Possible format values:
- %-Returns a percent semicolon%
- %b-binary
- %c-ascii value corresponding character
- %d-contains the decimal number of the sign (negative, 0, positive)
- %e-scientific notation using lowercase (e.g. 1.2e+2)
- % E-use uppercase scientific notation (e.g. 1.2E+2)
li>%u-Unsigned decimal number (greater than or equal to 0)
- %f-floating-point number (local setting)
- % F-floating point (not local)
- %g-Shorter%e and%f
%g-Shorter%E and%f
- %o-Eight decimal digits
- %s-string
- %x-16 decimal (lowercase)
- % x-16 Decimal (capital letter) the
appended format value. Must be placed between the% and the letter (for example,%.2f):
- ' (specifies what to use as a fill, and the default is a space.) It must be used with the width of the specified device. For example:% ' x20s (with "x" as padding)
- -(left adjustment variable value)
- [0-9] (minimum width of the specified variable value)
- . [ 0-9] (Specify number of decimal digits or maximum string length)
Note: If you use more than one of the above format values, they must be used in the order above. |
Arg1 |
Necessary. Specifies the parameter that is inserted into the first% symbol in the format string. |
Arg2 |
Optional. Specifies the parameter that is inserted into the second% symbol in the format string. |
arg++ |
Optional. Specifies the parameters that are inserted into the format string at the third to fourth-equal% symbol. |
Technical details
return value: |
Returns the formatted string. |
PHP version: |
4 + |
More examples of examples 1
Use the format value%f:
<?php$number = 123; $txt = sprintf ("%f", $number); Echo $txt; >
PHP sprintf ()