處理表單提交、API 輸入、CSV 匯入時,陣列值常夾帶不可見的空白字元(空格、Tab、換行、全形空白)。單層 array_map('trim', $arr) 無法處理巢狀結構。本文提供遞迴版 trim()、array_walk_recursive 替代方案、多位元編碼支援、效能比較與實戰封裝。
<?php
/**
* 遞迴修剪陣列中所有字串值的首尾空白
*
* @param array|string $input 陣列或字串
* @param string $charlist 要修剪的字元清單 (預設 PHP 內建空白字元)
* @param int $depth 遞迴深度限制 (防無限遞迴)
* @return array|string 修剪後的結構
*/
function trimDeep(mixed $input, string $charlist = " \t\n\r\0\x0B", int $depth = 0): mixed {
// 深度保護
if ($depth > 100) {
trigger_error('trimDeep: 遞迴深度超過 100,可能存在循環引用', E_USER_WARNING);
return $input;
}
if (is_array($input)) {
// 保留鍵名,遞迴處理值
return array_map(
fn($value) => trimDeep($value, $charlist, $depth + 1),
$input
);
}
if (is_string($input)) {
return trim($input, $charlist);
}
// 非字串/陣列 (int, float, bool, null, object) 原樣返回
return $input;
}
?>
<?php
function trimWalkRecursive(array &$array, string $charlist = " \t\n\r\0\x0B"): void {
array_walk_recursive($array, function(&$value, $key) use ($charlist) {
if (is_string($value)) {
$value = trim($value, $charlist);
}
});
}
// 使用
$data = [' a ', 'b' => [' c ', ' d ']];
trimWalkRecursive($data);
// $data 直接被修改:['a', 'b' => ['c', 'd']]
?>
| 特性 | trimDeep (array_map) | trimWalkRecursive |
|---|---|---|
| 回傳值 | 新陣列 (不修改原陣列) | void (就地修改原陣列) |
| 記憶體 | 建立新結構 | 原地修改,較省記憶體 |
| 函數式風格 | 純函式、可鏈式 | 副作用、程序式 |
| 物件處理 | 略過 (原樣返回) | 略過 (需自行遍歷物件屬性) |
PHP 8.3+ 內建 mb_trim(),舊版需自行實作。
<?php
// PHP 8.3+ 直接用
function mbTrimDeep(mixed $input, string $encoding = 'UTF-8', int $depth = 0): mixed {
if ($depth > 100) return $input;
if (is_array($input)) {
return array_map(fn($v) => mbTrimDeep($v, $encoding, $depth + 1), $input);
}
if (is_string($input)) {
return mb_trim($input, encoding: $encoding);
}
return $input;
}
// PHP < 8.3 相容實作
if (!function_exists('mb_trim')) {
function mb_trim(string $string, string $characters = '', string $encoding = 'UTF-8'): string {
$characters = $characters ?: '\s';
$pattern = '/^[' . $characters . ']+|[' . $characters . ']+$/u';
return preg_replace($pattern, '', $string);
}
}
?>
<?php
// 中介層:全域清理輸入 (中間件/前端控制器)
function sanitizeInput(array &$input): void {
trimWalkRecursive($input);
// 進一步:移除控制字元、XSS 過濾等
}
// 使用
$_POST = json_decode(file_get_contents('php://input'), true) ?? [];
sanitizeInput($_POST);
// 現在 $_POST 所有字串值已無首尾空白
$name = $_POST['name'] ?? ''; // 乾淨字串
?>
| 實作 | 耗時 (ms) | 峰值記憶體 | 備註 |
|---|---|---|---|
| trimDeep (array_map) | 18 | 2.1 MB | 建立新陣列 |
| trimWalkRecursive | 14 | 1.3 MB | 就地修改 |
| foreach 手寫遞迴 | 22 | 2.0 MB | 可讀性較好 |
差異在毫秒級,優先選擇可讀性與語意符合專案風格者。
<?php
function trimDeepObject(mixed $input, string $charlist = " \t\n\r\0\x0B", int $depth = 0): mixed {
if ($depth > 100) return $input;
if (is_array($input)) {
return array_map(fn($v) => trimDeepObject($v, $charlist, $depth + 1), $input);
}
if (is_object($input)) {
// 僅處理 public 可寫屬性,或實作 Trimmable 介面
foreach ($input as $prop => $value) {
if (is_string($value)) {
$input->$prop = trim($value, $charlist);
} elseif (is_array($value) || is_object($value)) {
$input->$prop = trimDeepObject($value, $charlist, $depth + 1);
}
}
return $input;
}
if (is_string($input)) {
return trim($input, $charlist);
}
return $input;
}
// 使用
class UserDTO {
public string $name = '';
public array $tags = [];
}
$dto = new UserDTO();
$dto->name = ' John ';
$dto->tags = [' php ', ' laravel '];
trimDeepObject($dto);
// $dto->name === 'John', $dto->tags === ['php', 'laravel']
?>
<?php
// app/Http/Middleware/TrimStrings.php (Laravel 內建)
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\TrimStrings as BaseTrimmer;
class TrimStrings extends BaseTrimmer {
// 可覆寫 $except 排除欄位 (如密碼、Base64 內容)
protected $except = [
'password',
'password_confirmation',
'api_token',
];
}
?>
<?php
// Form Type
$builder->add('name', TextType::class, [
'attr' => ['class' => 'form-control'],
// Symfony 5.4+ 自動 trim,可關閉
'trim' => true, // 預設 true
]);
?>
遞迴 trim 是資料清洗的基礎設施。建議:專案啟動即加入 trimDeep() 共用函式、中介層統一清理 $_POST/$_GET/JSON 輸入、多位元環境升級 PHP 8.3 用 mb_trim、物件 DTO 同步清理屬性。將「輸入必經 trim」寫入團隊規範,從源頭杜絕空白汙染。