字串處理是 Web 開發最高頻任務。PHP 提供超過 100 個字串函式,本文精選 50+ 高頻函式,按功能分類附實戰範例,作為開發隨查手冊。
長度與資訊
| 函式 | 說明 | 範例 |
strlen | 位元組長度 (非字元數) | strlen('中文') // 6 (UTF-8) |
mb_strlen | 多位元組字元長度 | mb_strlen('中文', 'UTF-8') // 2 |
str_word_count | 單字計數 | str_word_count('Hello world') // 2 |
count_chars | 字元頻率統計 | count_chars('abc', 1) // ['a'=>1,'b'=>1,'c'=>1] |
大小寫轉換
strtolower, strtoupper, ucfirst, ucwords, lcfirst
mb_strtolower, mb_strtoupper, mb_convert_case // 多位元組安全
搜尋與定位
| 函式 | 說明 | 回傳 |
strpos | 首次出現位置 (區分大小寫) | int/false |
stripos | 不區分大小寫 | int/false |
strrpos | 最後出現位置 | int/false |
strstr | 從首次出現到結尾 | string/false |
stristr | 不區分大小寫 | string/false |
str_contains | PHP 8+ 純檢查是否包含 | bool |
str_starts_with | PHP 8+ 檢查開頭 | bool |
str_ends_with | PHP 8+ 檢查結尾 | bool |
分割與合併
// 分割
explode(',', 'a,b,c') // ['a','b','c']
preg_split('/\s+/', 'a b c') // 正則分割
str_split('abc', 2) // ['ab', 'c']
mb_split('pattern', '字串') // 多位元組正則分割
// 合併
implode(',', ['a','b','c']) // 'a,b,c'
join(',', ['a','b','c']) // implode 別名
替換與修剪
| 函式 | 說明 |
str_replace | 字串替換 (支援陣列批量) |
str_ireplace | 不區分大小寫替換 |
substr_replace | 指定位置長度替換 |
trim | 移除首尾空白 (可指定字元表) |
ltrim/rtrim | 單側修剪 |
strtr | 字元級轉換 (單字元或陣列對應) |
子字串擷取
substr($str, $offset, $length) // 位元組級 (中文易斷碼)
mb_substr($str, $offset, $len, 'UTF-8') // 字元級安全
substr_count($haystack, $needle) // 計算出現次數
格式化與編碼
| 函式 | 用途 |
sprintf/printf | 格式化字串 (%s %d %f %.2f %x 等) |
number_format | 數字格式化 (千分位、小數位) |
htmlspecialchars | HTML 實體編碼 (防 XSS 必用) |
htmlentities | 所有字元轉實體 |
urlencode/rawurlencode | URL 編碼 (空格為 + / %20) |
urldecode/rawurldecode | URL 解碼 |
base64_encode/decode | Base64 編碼 |
json_encode/decode | JSON 序列化 |
md5/sha1/hash | 雜湊 (密碼請用 password_hash) |
進階處理
// 相似度比較
similar_text('apple', 'aple', $p); // $p = 80
levenshtein('kitten', 'sitting') // 編輯距離 = 3
soundex('Euler') == soundex('Eller') // 發音編碼比較
// 解析查詢字串
parse_str('a=1&b=2', $arr); // $arr = ['a'=>'1','b'=>'2']
// 字串填充
str_pad('5', 3, '0', STR_PAD_LEFT) // '005'
str_repeat('-', 10) // '----------'
// 斜線處理
addslashes/stripslashes // 歷史遺留,資料庫請用預處理
?>
多位元組 (mbstring) 必備原則
- 處理中文/日文/韓文等非 ASCII 務必使用 mb_* 系列
mb_internal_encoding('UTF-8') 設定內部編碼
- 正則加
u 修飾符:/pattern/u
- 資料庫連線、HTML meta、HTTP header 統一 UTF-8
善用字串函式庫,讓文字處理精準、安全、高效。