函式名稱: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語句將格式化字串輸出到螢幕上。