sprintf() 是 PHP 格式化字串的瑞士軍刀,通過格式化字符佔位符實現模板與數據分離。廣泛應用於 SQL 語句構建、API 回應模板、日誌格式化、國際化字串等場景。本文系統講解格式化字符語法、類型轉換規則、參數交換與實戰模式。
sprintf(string $format, mixed ...$values): string
// 格式化字符結構:%[參數編號$][標誌][寬度][.精度]類型
// 例:%2$.2f → 第2個參數、浮點數、保留2位小數
% | 字面百分號 | % |
| b | 二進制整數 | 1010 |
| c | ASCII 字符 | A |
| d | 有符號十進制整數 | -42 |
| e | 科學計數法(小寫) | 1.23e+2 |
| E | 科學計數法(大寫) | 1.23E+2 |
| u | 無符號十進制整數 | 42 |
| f | 浮點數(區域感知) | 3.14 |
| F | 浮點數(非區域感知) | 3.14 |
| g | %e 或 %f 較短者 | 3.14 |
| G | %E 或 %F 較短者 | 3.14 |
| o | 八進制整數 | 52 |
| s | 字串 | hello |
| x | 十六進制(小寫) | 2a |
| X | 十六進制(大寫) | 2A |
%[參數編號$][標誌][寬度][.精度]類型
│ │ │ │
│ │ │ └─ 類型字符(必須)
│ │ └─ 精度:小數位數/字串最大長度
│ └─ 寬度:最小字符寬度,不足填充
└─ 標誌:- 左對齊、+ 強制符號、0 零填充、空格 正數前加空格、' 自定義填充字符
<?php
$num = 42;
$neg = -42;
$pi = 3.14159;
$str = 'hi';
echo sprintf("%+d %+d\n", $num, $neg); // +42 -42 (強制符號)
echo sprintf("%05d\n", $num); // 00042 (零填充寬度5)
echo sprintf("%-10s|\n", $str); // "hi |" (左對齊寬度10)
echo sprintf("%'*-10s|\n", $str); // "hi********|" (自定填充字符*)
echo sprintf("%.2f\n", $pi); // 3.14 (精度2)
echo sprintf("%10.2f\n", $pi); // " 3.14" (寬度10+精度2)
?>
使用 n$ 指定參數順序,支援重複使用、任意順序:
<?php
$format = '姓名:%2$s,年齡:%1$d,城市:%3$s';
echo sprintf($format, 25, '張三', '北京');
// 輸出:姓名:張三,年齡:25,城市:北京
// 重複使用同一參數
echo sprintf('%1$s %1$s %1$s', 'echo'); // echo echo echo
?>
<?php
$xmlTpl = <<
%d
XML;
$result = sprintf($xmlTpl,
$fromUsername, // %1$s
$toUsername, // %2$s
time(), // %3$d
$msgType, // %4$s
$contentStr // %5$s
);
echo $result;
?>
<?php
// 僅用於靜態分析/日誌輸出,實際執行請用 PDO 預處理!
$table = 'users';
$cols = ['username', 'email', 'password_hash', 'status', 'role'];
$placeholders = implode(',', array_fill(0, count($cols), '?'));
$sql = sprintf(
'INSERT INTO %s (%s) VALUES (%s)',
$table,
implode(',', $cols),
$placeholders
);
// INSERT INTO users (username,email,password_hash,status,role) VALUES (?,?,?,?,?)
// 參數化執行
$stmt = $pdo->prepare($sql);
$stmt->execute([$username, $email, $hash, 1, 'user']);
?>
<?php
function logEntry(string $level, string $message, string $context = ''): string {
return sprintf(
"[%s] %-5s | %-30s | %s\n",
date('Y-m-d H:i:s'),
strtoupper($level),
$message,
$context
);
}
echo logEntry('info', 'User login', 'uid=1001 ip=1.2.3.4');
// [2024-01-15 14:30:59] INFO | User login | uid=1001 ip=1.2.3.4
?>
<?php
$_ = function(string $key, ...$args) {
$templates = [
'welcome' => '歡迎 %1$s,您是第 %2$d 位訪客',
'balance' => '餘額:%1$.2f 元',
];
return sprintf($templates[$key] ?? $key, ...$args);
};
echo _('welcome', '張三', 10086); // 歡迎 張三,您是第 10086 位訪客
echo _('balance', 1234.56); // 餘額:1234.56 元
?>
printf():直接輸出到標準輸出,返回字串長度sprintf():返回格式化字串,**最常用**fprintf($handle, ...):寫入文件句柄vprintf()/vsprintf()/vfprintf():接受陣列參數 vsprintf($fmt, $args)<?php
// 類型不匹配會觸發 Warning 並嘗試轉換
sprintf('%d', 'abc'); // Warning: expects int, string given → 輸出 0
sprintf('%s', 123); // 正常轉換為 "123"
sprintf('%f', '3.14'); // 正常轉換為 3.140000
// 嚴格模式建議:預先類型轉換
$num = (int)($input ?? 0);
echo sprintf('%d', $num);
?>
sprintf 比字串連接 . 稍慢(解析格式字串開銷)sprintf 效能完全足夠sprintf() 以「格式化字符 + 參數編號」實現模板與數據解耦,核心優勢:
%d 強制整數、.2f 固定小數位%2$s %1$d 靈活控制順序%-10s %05d 產生整齊輸出掌握 %[n$][flags][width][.precision]type 完整語法,能讓字串構建代碼從「拼接地獄」進化為「模板驅動」,是 PHP 開發者必備的格式化技能。