Home > Article > Backend Development > PHP sprintf function use case analysis
Copy the code The code is as follows:
//sprintf() function, the return value is the 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 return value is the formatted string length
int printf ( string $format [, mixed $args [, mixed $... ]] )
$num = 3.14;
printf("Character padding %'#6.2s", $num); //##3.14
//The character length is 6, with 2 after the dot, less than 6 digits, # padding
Parameters | Description |
---|---|
format | Required. Convert format. |
arg1 | Required. Specifies the parameters to be inserted at the first % sign in the format string. |
arg2 | Optional. Specifies the parameter to be inserted into the format string at the second % sign. |
arg++ | Optional. Specifies the parameters to be inserted into the format string at the third, fourth, etc. % symbols. |
Description
Parameter format is the converted format, starting with the percent sign ("%") and ending with the conversion character. Possible format values below:
arg1, arg2, ++, etc. are inserted into the main string at the percent sign (%) symbol. This function is executed step by step. At the first % sign, insert arg1, at the second % sign, arg2, and so on.
Example
Example 1
Copy code The code is as follows:
$str = "Hello";
$number = 123;
$txt = sprintf("%s world. Day number %u",$str,$number);
echo $txt;
?>
Copy the code The code is as follows:
< ;?php
$number = 123;
$txt = sprintf("%f",$number);
echo $txt;
?>
Copy code The code is as follows:
$number = 123;
$txt = sprintf("With 2 decimals: %1$.2f
With no decimals: %1$u",$number );
echo $txt;
?>
The above has introduced the use case analysis of the PHP sprintf function, including the relevant aspects. I hope it will be helpful to friends who are interested in PHP tutorials.