Document directory
Copy codeThe Code is as follows: <? Php
// Sprintf () function. The returned value is a formatted string.
String sprintf (string $ format [, mixed $ args [, mixed $...])
$ Y = 11;
$ M = 3;
$ D = 9;
$ Date = sprinf ('% 04d-% 02d-% 02d', $ y, $ m, $ d );
Echo $ date; // 0011-0
// Printf () function. The returned value is the formatted string length.
Int printf (string $ format [, mixed $ args [, mixed $...])
$ Num = 3.14;
Printf ("Character filling % '# 6.2s", $ num); // #3.14
// The character length is 6, followed by a few digits and less than 6 characters. # Fill
Differences between sprintf () and printf ()
The syntax format is the same, but the returned values are different.
Definition and usage
The sprintf () function writes formatted strings to a variable.
Syntax
Sprintf (format, arg1, arg2, arg ++)
Parameters |
Description |
Format |
Required. Conversion format. |
Arg1 |
Required. Specifies the parameter inserted at the first % symbol in the format string. |
Arg2 |
Optional. Specifies the parameter inserted at the second % symbol in the format string. |
Arg ++ |
Optional. Specifies the parameters inserted to the third, fourth, and other % symbols in the format string. |
Description
ParametersFormatIs the conversion format, starting from the percent sign ("%") to the end of the conversion character. PossibleFormatValue:
- %-Percentage sign returned
- % B-binary number
- % C-Characters Based on ASCII values
- % D-Signed decimal number
- % E-resumable counting (for example, 1.5e + 3)
- % U-Unsigned decimal number
- % F-floating point number (local settings aware)
- % F-floating point number (not local settings aware)
- % O-octal values
- % S-string
- % X-hexadecimal (lowercase letter)
- % X-hexadecimal (uppercase letters)
Parameters such as arg1, arg2, ++ are inserted to the percent sign (%) in the main string. This function is executed step by step. In the first % symbol, insert arg1, at the second % symbol, insert arg2, and so on.
Example
Example 1
Copy codeThe Code is as follows: <? Php
$ Str = "Hello ";
$ Number = 123;
$ Txt = sprintf ("% s world. Day number % u", $ str, $ number );
Echo $ txt;
?>
Output:
Hello world. Day number 123
Example 2Copy codeThe Code is as follows: <? Php
$ Number = 123;
$ Txt = sprintf ("% f", $ number );
Echo $ txt;
?>
Output:
123.000000
Example 3Copy codeThe Code is as follows: <? Php
$ Number = 123;
$ Txt = sprintf ("With 2 decimals: % 1 \ $. 2f <br/> With no decimals: % 1 \ $ u", $ number );
Echo $ txt;
?>
Output:
With 2 decimals: 123.00
With no decimals: 123
More detailed can refer to the http://www.jb51.net/w3school/php/func_string_sprintf.htm