Definition and usage
The sprintf () function is used to write formatted strings into a variable.
Syntax
Sprintf (format, arg1, arg2, arg ++) parameter description
Format is required. Conversion format.
Arg1 is required. Specifies the parameter inserted at the first % symbol in the format string.
Optional. Specifies the parameter inserted at the second % symbol in the format string.
Optional. Specifies the parameters inserted to the third, fourth, and other % symbols in the format string.
Description
The format parameter is the conversion format. It starts with the percent sign ("%") and ends with the conversion character. The following possible format values:
• %-Return percent sign
• % 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.
Tips and comments
Note: If the % symbol is greater than the arg parameter, you must use a placeholder. The placeholder is inserted after the % symbol, which consists of numbers and "$. See Example 3.
Example
Example 1
The code is as follows: |
Copy code |
? <? Php $ str = "Hello"; $ number = 123; $ txt = sprintf ("% s world. day number % u ", $ str, $ number); echo $ txt;?> |
Output:
? Hello world. Day number 123
Example 2
The code is as follows: |
Copy code |
? <? Php $ number = 123; $ txt = sprintf ("% f", $ number); echo $ txt;?> |
Output:
? 123.000000
Example 3
The code is as follows: |
Copy code |
? <? 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
Example 4
The code is as follows: |
Copy code |
? <? Php $ ctype_primary = strtolower ('application'); $ ctype_secondary = strtolower ('PDF '); $ mimetype = sprintf (' % s/% s', $ ctype_primary, $ ctype_secondary); echo $ mimetype;?> Output: ? Application/pdf |