函数名称:sprintf()
适用版本:所有版本
函数描述:sprintf()函数根据指定的格式化字符串生成一个格式化的字符串。
用法:sprintf(string $format, mixed ...$values): string
参数:
- $format:格式化字符串,定义了输出字符串的格式。可以包含普通文本和格式化指令。
- $values:可选参数,用于替换格式化字符串中的格式化指令。可以是一个或多个值,根据格式化字符串中的指令数量决定。
返回值:返回一个格式化后的字符串。
示例:
$number = 10;
$name = "John";
$price = 19.99;
// 格式化字符串中使用 %d 表示整数,%s 表示字符串,%f 表示浮点数
$result = sprintf("There are %d apples.", $number);
echo $result; // 输出:There are 10 apples.
$result = sprintf("My name is %s.", $name);
echo $result; // 输出:My name is John.
$result = sprintf("The price is %.2f dollars.", $price);
echo $result; // 输出:The price is 19.99 dollars.
在上面的示例中,sprintf()函数根据给定的格式化字符串生成了相应的格式化字符串。参数$format中的格式化指令(%d、%s、%f)被参数$values中的值($number、$name、$price)替换,生成了最终的格式化字符串。最后使用echo语句将格式化字符串输出到屏幕上。