首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 字串處理 5 大實用技巧:格式化、填充、比較、截取與替換完全攻略

     編輯:PHP 綜合知識

前言

字串處理是 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
*/

技巧三:大小寫轉換與字串比較

大小寫轉換函數族

去除空白字元

trim($str)    // 兩側
ltrim($str)   // 左側
rtrim($str)   // 右側
// 可指定字元遮罩:trim($str, " \t\n\r\0\x0B")

字串比較 (二進位安全)

函數功能範例
strtolower全轉小寫"HELLO" → "hello"
strtoupper全轉大寫"hello" → "HELLO"
ucfirst首字元大寫"hello world" → "Hello world"
ucwords每單字首字大寫"hello world" → "Hello World"
lcfirst首字元小寫 (PHP 5.3+)"Hello" → "hello"
函數特性回傳值
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_padSTR_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()` 更語意化
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved