「一切資料最終都是字串在流動」。PHP 處理字串的場景極多,本文聚焦三大高頻主題:JSON 序列化、字串與陣列互轉、編碼處理,並給出最佳實踐代碼。
json_encode($value, $flags = 0, $depth = 512):PHP 變數 → JSON 字串。json_decode($json, $assoc = false, $depth = 512, $options = 0):JSON 字串 → PHP 變數($assoc=true 回傳關聯陣列)。| 常數 | 用途 |
|---|---|
JSON_UNESCAPED_UNICODE | 中文不轉義為 \uXXXX,直接輸出可讀字元(PHP 5.4+) |
JSON_UNESCAPED_SLASHES | 不轉義 / ,輸出 URL 更乾淨 |
JSON_NUMERIC_CHECK | 數值字串自動轉為數字型別 |
JSON_PRETTY_PRINT | 美化縮排,適合除錯/日誌 |
<?php
$arr = ['name' => 'Eric', 'age' => 23, 'tags' => ['php', 'json']];
echo json_encode($arr, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
// 輸出:
// {
// "name": "Eric",
// "age": 23,
// "tags": ["php", "json"]
// }
$json = '{"id":1,"title":"測試"}';
$data = json_decode($json, true); // 關聯陣列
var_dump($data['title']); // string(6) "測試"
?>
<?php
json_decode($invalidJson);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException('JSON 錯誤: ' . json_last_error_msg());
}
?>
<?php
$str = "Hello world It's a beautiful day";
$parts = explode(' ', $str); // 以空白分割
// ['Hello', 'world', "It's", 'a', 'beautiful', 'day']
?>
注意:explode 不支援正則,複雜分割請用 preg_split()。
<?php
$arr = ['hello', 'world', '!'];
echo implode(' ', $arr); // "hello world !"
?>
implode($glue, $pieces) 參數順序可互換(歷史相容),建議固定用 ($glue, $pieces)。
<?php
// UTF-8 → Big5(繁體中文常用)
$big5 = mb_convert_encoding($utf8Str, 'Big5', 'UTF-8');
// 或
$big5 = iconv('UTF-8', 'BIG5//IGNORE', $utf8Str); // //IGNORE 忽略無法轉換字元
// 偵測編碼
$encoding = mb_detect_encoding($str, ['UTF-8', 'Big5', 'GBK'], true);
?>
建議:專案統一使用 UTF-8,資料庫、連線、HTML、PHP 檔案編碼全端一致,避免 99% 編碼問題。
trim()、preg_replace('/\s+/', ' ', $str)。mb_substr()、mb_strimwidth()(支援多位元組)。htmlspecialchars($str, ENT_QUOTES, 'UTF-8') 防 XSS。掌握 json_encode/decode 旗標、explode/implode 分合、mb_* 多位元組函數,即可應付 PHP 字串處理 95% 場景。記住:統一 UTF-8、參數化查詢、輸出轉義 三大鐵律。