sprintf()function 是 PHP 中的一個內置函數,用於格式化字符串,其方式類似於 C 語言的 printf() 函數。它允許您通過用相應的值替換占位符來創建格式化字符串。
用法:
string sprintf(string $format, mixed ...$values)
Parameters: 該函數接受兩個參數,如下所述:
- $format: 這是一個指定輸出格式的字符串。它包含以百分號 (%) 開頭的占位符,後跟表示應插入到該位置的值類型的字符。
- $values: 這些值將替換格式字符串中的占位符。您可以提供任意數量的參數,具體取決於格式字符串中占位符的數量及其類型。
返回值: sprintf()函數返回由該函數生成的字符串。
程序1:下麵的程序演示了sprintf()函數。
PHP
<?php
$first_name = "Ram";
$last_name = "Kumar";
$age = 28;
$balance = 1200.50;
$formatted_string = sprintf(
"Name: %s %s\nAge: %d\nBalance: $%.2f",
$first_name, $last_name, $age, $balance
);
echo $formatted_string;
?>
輸出
Name: Ram Kumar Age: 28 Balance: $1200.50
程序2:下麵的程序演示了sprintf()函數。
PHP
<?php
$product = "Widget";
$quantity = 10;
$pricePerUnit = 24.95;
$totalPrice = $quantity * $pricePerUnit;
$formatted_invoice = sprintf(
"Invoice:\nProduct: %s\nQuantity: %d\nPrice"
. " per Unit: $%.2f\nTotal Price: $%.2f",
$product, $quantity,
$pricePerUnit, $totalPrice
);
echo $formatted_invoice;
?>
輸出
Invoice: Product: Widget Quantity: 10 Price per Unit: $24.95 Total Price: $249.50
參考:https://www.php.net/manual/en/function.sprintf.php
相關用法
- PHP sprintf()用法及代碼示例
- PHP split()用法及代碼示例
- PHP spliti()用法及代碼示例
- PHP sin()用法及代碼示例
- PHP sqrt()用法及代碼示例
- PHP string Implode()用法及代碼示例
- PHP string crypt()用法及代碼示例
- PHP string join()用法及代碼示例
- PHP string lcfirst()用法及代碼示例
- PHP string levenshtein()用法及代碼示例
- PHP string ltrim()用法及代碼示例
- PHP string md5()用法及代碼示例
- PHP string md5_file()用法及代碼示例
- PHP string money_format()用法及代碼示例
- PHP string number_format()用法及代碼示例
- PHP string ord()用法及代碼示例
- PHP string parse_str()用法及代碼示例
- PHP string printf()用法及代碼示例
- PHP string quotemeta()用法及代碼示例
- PHP string rtrim()用法及代碼示例
- PHP string setlocale()用法及代碼示例
- PHP string sha1()用法及代碼示例
- PHP string sha1_file()用法及代碼示例
- PHP string similar_text()用法及代碼示例
- PHP string str_ireplace()用法及代碼示例
注:本文由純淨天空篩選整理自neeraj3304大神的英文原創作品 PHP sprintf() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。