PHP sprintf of function use case resolution

  • 2020-05-07 19:18:24
  • OfStack

 
<?php 
//sprintf() Function that returns 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 that returns the formatted string length  
int printf ( string $format [, mixed $args [, mixed $... ]] ) 
$num = 3.14; 
printf( "Character fill  %'#6.2s " , $num); //##3.14 
// Character length is 6 After you count them 2 Insufficient, 6 position # fill  

sprintf() is different from printf()
Syntax format 1, but the return value is different


Definition and usage
The sprintf() function writes the formatted string to a variable.

grammar
sprintf(format,arg1,arg2,arg++)
parameter describe format A necessity. Convert the format. arg1 A necessity. Specifies the parameter to be 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 format string at 3.4 and so on.

instructions

The format parameter 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 - characters according to the ASCII value %d - signed decimal number %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) Base number %o - 8 %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, in the second % symbol, insert arg2, and so on.
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
More detail you can refer to. / / www ofstack. com w3school/php/func_string_sprintf htm


Related articles: