前言
字串處理是 PHP 開發最高頻操作。本文精選 5 大核心場景——格式化輸出、字串填充、大小寫與比較、查找截取、替換操作,提供標準函數用法、參數詳解與實戰範例,助你寫出更優雅、高效的程式碼。
技巧一:printf / sprintf 格式化輸出
比字串串接更強大、更易讀,支援型別轉換、寬度、精度、進制等。
核心語法
printf(string $format, mixed ...$values): int // 直接輸出,回傳長度
sprintf(string $format, mixed ...$values): string // 回傳格式化字串
常用格式化符號
| 符號 | 意義 | 範例 |
| %d | 有號十進位整數 | printf("%d", 3.14) → 3 |
| %s | 字串 | printf("%s", "Hello") → Hello |
| %f | 浮點數 (預設小數 6 位) | printf("%.2f", 3.14159) → 3.14 |
| %b | 二進位 | printf("%b", 10) → 1010 |
| %x / %X | 十六進位 (小寫/大寫) | printf("%X", 255) → FF |
| %% | 字面 % | printf("100%%") → 100% |
寬度與精度控制
printf("%10.2f", 3.14); // 寬度 10,右對齊,小數 2 位 → " 3.14"
printf("%-10.2f", 3.14); // 左對齊 → "3.14 "
printf("%010.2f", 3.14); // 零填充 → "0000003.14"
printf("%.9s", "abcdefghijklmn"); // 截取前 9 字元 → "abcdefghi"
printf("%5.2f, %f, %7.3f", 3.14159, 3.14159, 3.14159); // 多欄位對齊
實戰:產生固定寬度報表
$data = [
['Apple', 123, 1.5],
['Banana', 45, 0.8],
['Cherry', 6789, 3.14159]
];
foreach ($data as $row) {
printf("%-10s %8d %10.2f\n", $row[0], $row[1], $row[2]);
}
/* 輸出:
Apple 123 1.50
Banana 45 0.80
Cherry 6789 3.14
*/
技巧二:str_pad 字串填充對齊
str_pad(string $input, int $length, string $pad_string = " ", int $pad_type = STR_PAD_RIGHT): string
填充類型常數
STR_PAD_RIGHT (預設):右側填充
STR_PAD_LEFT:左側填充 (數字對齊常用)
STR_PAD_BOTH:兩側填充 (置中效果)
實戰範例
$index = ["one" => 1, "two" => 155, "three" => 1679];
// 標題置中
echo str_pad("這是標題", 50, " ", STR_PAD_BOTH) . "\n";
// 索引欄左對齊點填充,數值欄右對齊零填充
foreach ($index as $key => $val) {
echo str_pad($key, 30, ".", STR_PAD_RIGHT)
. str_pad($val, 20, "0", STR_PAD_LEFT) . "\n";
}
/* 輸出:
這是標題
one..............................00000000000000000001
two..............................00000000000000000155
three............................0000000000000001679
*/
技巧三:大小寫轉換與字串比較
大小寫轉換函數族
| 函數 | 功能 | 範例 |
| strtolower | 全轉小寫 | "HELLO" → "hello" |
| strtoupper | 全轉大寫 | "hello" → "HELLO" |
| ucfirst | 首字元大寫 | "hello world" → "Hello world" |
| ucwords | 每單字首字大寫 | "hello world" → "Hello World" |
| lcfirst | 首字元小寫 (PHP 5.3+) | "Hello" → "hello" |
去除空白字元
trim($str) // 兩側
ltrim($str) // 左側
rtrim($str) // 右側
// 可指定字元遮罩:trim($str, " \t\n\r\0\x0B")
字串比較 (二進位安全)
| 函數 | 特性 | 回傳值 |
| strcmp($a, $b) | 區分大小寫 | <0, =0, >0 |
| strncmp($a, $b, $len) | 限制比較長度 | 同上 |
| strcasecmp($a, $b) | 不區分大小寫 | 同上 |
| strncasecmp($a, $b, $len) | 不區分大小寫+長度限制 | 同上 |
| strnatcmp / strnatcasecmp | 自然排序比較 (PHP 4+) | "file2" < "file10" |
echo strcmp("aardvark", "aardwolf"); // -1 (a < w)
echo strncmp("aardvark", "aardwolf", 4); // 0 (前 4 字元相同)
echo strcasecmp("HELLO", "hello"); // 0
技巧四:查找與截取子字串
substr 多功能截取
$str = "abcdefgh";
echo substr($str, 2); // cdefgh (從索引 2 到結尾)
echo substr($str, 2, 3); // cde (長度 3)
echo substr($str, -1); // h (倒數 1 字元)
echo substr($str, -5, 2); // de (倒數 5 起長度 2)
echo substr($str, -5, -2); // def (倒數 5 起到倒數 3)
查找位置
| 函數 | 功能 | 回傳 |
| strpos($haystack, $needle, $offset) | 首次出現位置 | int/false |
| stripos() | 不區分大小寫 | int/false |
| strrpos($haystack, $needle) | 最後一次出現 (單字元) | int/false |
| strripos() | 不區分大小寫最後位置 | int/false |
提取子字串 (從找到位置開始)
$email = "user@example.com";
echo strstr($email, "@"); // @example.com (含針)
echo strstr($email, "@", true); // user (PHP 5.3+,排除針)
echo strchr($email, "@"); // 同 strstr
分割與合併
$str = "apple,banana,orange";
$arr = explode(",", $str); // ['apple','banana','orange']
$str2 = implode(" | ", $arr); // "apple | banana | orange"
// 限制分割次數
explode(",", "a,b,c,d", 2); // ['a', 'b,c,d']
explode(",", "a,b,c,d", -1); // ['a','b','c'] (PHP 5.1+,排除最後)
技巧五:字串替換
substr_replace 精準位置替換
substr_replace(string $string, string $replace, int $offset, int $length = null): string
$str = "Hello World";
echo substr_replace($str, "PHP", 6); // Hello PHP (從 6 替換到結尾)
echo substr_replace($str, "PHP", 6, 5); // Hello PHP (替換 5 字元)
echo substr_replace($str, "PHP", -6, 5); // Hello PHP (倒數 6 起替換 5)
echo substr_replace($str, "", 5, 1); // HelloWorld (刪除空格)
str_replace / str_ireplace 批次替換
$str = "A B C";
echo str_replace(["A","B"], ["X","Y"], $str); // X Y C
echo str_ireplace("a", "X", "A b C"); // X b C (不區分大小寫)
// 計算替換次數
$count = 0;
str_replace("a", "b", "aaa", $count); // $count = 3
preg_replace 正則替換 (進階)
// 移除多餘空白
echo preg_replace('/\s+/', ' ', "a b\tc\nd"); // "a b c d"
// 回調函數替換 (PHP 7.4+ 箭頭函數)
echo preg_replace_callback('/\d+/', fn($m) => $m[0]*2, "a1b2c3"); // "a2b4c6"
總結對照表
| 場景 | 推薦函數 | 關鍵提醒 |
| 格式化數字/報表 | sprintf/printf | 型別轉換自動,注意 %f 預設 6 位小數 |
| 固定寬度對齊 | str_pad | STR_PAD_LEFT 數字對齊,STR_PAD_BOTH 置中 |
| 大小寫轉換 | strtolower 等 | 多位元組字元需 mb_strtolower (需 mbstring) |
| 二進位安全比較 | strcmp 系列 | === 比較字串時優先用 strcmp 避免型別轉換 |
| 截取子字串 | substr | 中文請用 mb_substr,支援負索引 |
| 查找位置 | strpos/stripos | 必須用 !== false 判斷,0 也是有效位置 |
| 分割字串 | explode | 正則分割用 preg_split |
| 簡單替換 | str_replace | 陣列替換順序重要,長字串優先避免重複替換 |
| 複雜模式替換 | preg_replace | 效能較差,簡單替換優先用 str_replace |
現代最佳實踐提醒
- 多位元組字元 (中文/日文/Emoji):全系列改用
mb_* 對應函數,並設定 `mb_internal_encoding('UTF-8')`
- 效能:簡單操作優先用字串函數,非必要勿用正則
- 安全:輸出到 HTML 必經 `htmlspecialchars()`,SQL 參數綁定
- PHP 8.0+ 新函數:`str_contains()`, `str_starts_with()`, `str_ends_with()` 更語意化
- 上一篇文章: MySQL 日期時間函數完整參考手冊:格式化、運算、轉換與實戰範例
- 下一篇文章: PHP 表單核取方塊 (Checkbox) 陣列傳值完整指南:命名規則、接收處理與常見陷阱
Copyright ©
程式碼之家 All Rights Reserved