PHP sprintf function
The PHP sprintf function can insert formatted character elements into a specific position in a string variable . The processing method for inserting is the same as that of the printf function, but the sprintf function only performs the insertion work, and is not responsible for the actions of output on the web page. That is to say, after the sprintf function is processed, it will only return a new string variable for subsequent other processing. If it is to be output to a web page, it must be done through echo or print . If no other processing is needed, just output the converted string variable directly, and you can use the printf function .
PHP sprintf basic syntax
string sprintf (string $format, $args1, $args2, $args3, $arg4, $arg5 ...)
The first parameter in the parentheses of the sprintf function, $format, is the original formatting conversion string , and the following series of $args are the character parameters to be inserted into the $format string , and each character parameter will be sequentially inserted into the original format Convert the percent sign (%) in the string ($format) and complete the formatting. For example, $args1 is inserted into the first% position of $format, $args2 is inserted into the second% position, and $args3 is inserted To the 3rd% position... and so on, there are detailed references in the example.
The $format parameter in the original string is usually written as% plus the delimitation code. The possible forms are as follows
| %% | Returns the percentage sign, no parameters are required |
| %b | Binary integer parameter |
| %c | The parameter is treated as an ASCII value character integer |
| %d | Decimal integer parameter |
| %e | Parameters will be treated as scientific notation, such as 1.2e+2 |
| %E | Similar to %e, but presented in uppercase English letters, such as 1.2E+2 |
| %u | The parameter is treated as an unsigned decimal integer |
| %f | Floating point number (locale aware) |
| %F | Floating point numbers (non-locale aware, new in PHP 4.3.10 and PHP 5.0.3) |
| %g | Shorter than %e and %f. |
| %G | Shorter than %E and %F. |
| %o | Octal integer parameter |
| %s | String |
| %x | Hexadecimal (lowercase letters) |
| %X | Hexadecimal (uppercase letters) |
This table can also be compared to the $format parameter used in the PHP printf function .
PHP sprintf reference example 1: Bring in string, number and floating point number conversion
$string ='to';
$number = '5';
$format ='Welcome %s Wibibi.%f is float of %u.';
echo sprintf($format,$string,$number,$number );
?>
PHP sprintf reference example two, control the number of decimal places
$number = '5';
$format = "%1\$.3f is float of %u.";
echo sprintf($format,$number,$number);
?>
Post a Comment
0 Comments