PHP sprintf of function application of definition and usage

  • 2020-05-19 04:18:04
  • OfStack

grammar

sprintf(format,arg1,arg2,arg++) parameter describe format A necessity. Convert the format. arg1 A necessity. Specifies the parameter inserted at the first % symbol in the format string. arg2 Optional. Specifies the parameter to be inserted at the second % symbol in the format string. arg++ Optional. Specifies the parameter to be inserted into the % symbol of the format string at 3. 4, etc.

instructions

The parameter format is the format of the conversion, starting with the percentage symbol ("%") and ending with the conversion character. The following possible format values:
%% - returns the percentage symbol
%b - 2 base number
%c - character according to the ASCII value
%d - number in decimal with sign
%e - continuable counting (e.g. 1.5e+3)
%u - unsigned decimal number
%f - floating point number (local settings aware)
%F - floating point number (not local settings aware)
% o-8 base number
%s - string
% x-106 base Numbers (lowercase letters)
% X-106 base Numbers (capital letters)
Parameters such as arg1, arg2, ++ are inserted into the percent (%) symbol 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

Hints and comments
Note: if the % symbol is more than the arg parameter, you must use placeholders. The placeholder is inserted after the % symbol and consists of a number and "\$". See example 3.

example
Example 1

 
? 
<?php 
$str = "Hello"; 
$number = 123; 
$txt = sprintf("%s world. Day number %u",$str,$number); 
echo $txt; 
?> 

Output:

Hello world. Day number 123

Example 2
 
<?php 
$number = 123; 
$txt = sprintf("%f",$number); 
echo $txt; 
?> 


Output:

123.000000

Example 3
 
<?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
 
<?php 
$ctype_primary = strtolower('application'); 
$ctype_secondary = strtolower('pdf'); 
$mimetype = sprintf('%s/%s', $ctype_primary, $ctype_secondary); 
echo $mimetype; 
?> 

Output:
 
application/pdf 


Related articles: