前言
PHP 提供四個去除字串首尾空白字元的函數。本文詳細說明各函數差異、預設字元清單、自訂字元遮罩、多位元組支援與實務應用模式。
四大函數對照
| 函數 | 別名 | 作用範圍 | 說明 |
trim() | - | 兩端 | 同時移除開頭與結尾 |
ltrim() | - | 左側/開頭 | Left trim |
rtrim() | chop() | 右側/結尾 | Right trim,chop 為別名 |
預設移除字元清單
<?php
// 預設移除以下字元(ASCII 控制字元 + 空白)
$defaultChars = [
" " => '空白 (0x20)',
"\t" => '定位字元 (0x09)',
"\n" => '換行 (0x0A)',
"\r" => '歸位 (0x0D)',
"\0" => 'NULL (0x00)',
"\v" => '垂直定位 (0x0B)',
];
// 驗證
$test = " \t\n\r\0\vHello \t\n\r\0\v ";
echo "原始: [" . bin2hex($test) . "]\n";
echo "trim: [" . bin2hex(trim($test)) . "]\n";
// 輸出: 原始: [20090a0d000b48656c6c6f20090a0d000b]
// trim: [48656c6c6f]
?>
基本用法示範
<?php
$text = "\t\t jb51.net! \t\t ";
echo "leftTrimmed = (" . ltrim($text) . ")\n"; // jb51.net!
echo "rightTrimmed = (" . rtrim($text) . ")\n"; // jb51.net!
echo "bothTrimmed = (" . trim($text) . ")\n"; // jb51.net!
echo "chop = (" . chop($text) . ")\n"; // jb51.net! (同 rtrim)
?>
自訂字元遮罩(第 2 參數)
<?php
$str = "....Hello World...";
// 移除指定字元
echo trim($str, '.'); // Hello World
echo ltrim($str, '.'); // Hello World...
echo rtrim($str, '.'); // ....Hello World
// 移除多種字元
$str = "xyzHello Worldzyx";
echo trim($str, 'xyz'); // Hello World (移除 x、y、z)
// 範圍指定
$str = "abcDEF123";
echo trim($str, 'a..z'); // DEF123 (移除 a-z)
echo trim($str, '0..9'); // abcDEF (移除 0-9)
// 實用:移除所有空白類字元(含全形空白)
$str = " \u{3000}Hello\u{3000} "; // 全形空白 U+3000
echo trim($str, " \t\n\r\0\v\x{3000}"); // Hello
?>
多位元組字元支援(UTF-8 中文等)
<?php
// 內建 trim/ltrim/rtrim 在 PHP 7.0+ 已支援 UTF-8 多位元組字元
$str = " 你好世界 ";
echo trim($str); // 你好世界 ✅
// 但自訂字元遮罩時,字元必須為單一字元或範圍
// 移除全形空白 U+3000
$str = "\u{3000}Hello\u{3000}";
echo trim($str, "\u{3000}"); // Hello ✅
// 注意:chop() 為 rtrim() 別名,行為完全相同
?>
實務應用模式
1. 使用者輸入淨化
<?php
function sanitizeInput(string $input, bool $trimAll = true): string {
// 1. 修剪首尾空白
$input = trim($input);
// 2. 正規化內部空白(可選)
if ($trimAll) {
$input = preg_replace('/\s+/u', ' ', $input);
}
// 3. 移除控制字元(保留換行/定位可選)
$input = preg_replace('/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/', '', $input);
return $input;
}
$_POST['username'] = sanitizeInput($_POST['username'] ?? '');
$_POST['bio'] = sanitizeInput($_POST['bio'] ?? '', false); // 保留段落
?>
2. CSV/TSV 欄位清理
<?php
function cleanCsvField(string $field): string {
// 移除首尾空白、雙引號、前置單引號(Excel 文字格式標記)
$field = trim($field, " \t\n\r\0\x0B\"'");
// 內部雙引號雙寫(CSV 標準)
$field = str_replace('"', '""', $field);
return $field;
}
?>
3. 路徑正規化
<?php
function normalizePath(string $path): string {
// 移除首尾斜線與空白
$path = trim($path, " \t\n\r/\\");
// 統一分隔符
$path = str_replace('\\', '/', $path);
// 合併重複斜線
$path = preg_replace('/\/+/', '/', $path);
return $path;
}
echo normalizePath(" /var/www//html/ "); // var/www/html
echo normalizePath("C:\\Users\\Name\\ "); // C:/Users/Name
?>
4. 關鍵字提取清理
<?php
function extractKeywords(string $text): array {
// 分割、修剪、過濾空值、去重、小寫
return array_unique(array_filter(array_map(
fn($w) => mb_strtolower(trim($w)),
preg_split('/[\s,;,;、|]+/u', $text)
)));
}
print_r(extractKeywords(" PHP , Laravel , vue.js , php "));
// ['php', 'laravel', 'vue.js']
?>
常見陷阱
| 情況 | 結果 | 說明 |
trim("abc", "ab") | "c" | 移除字元集合 {a,b},非字串 "ab" |
trim("abc", "a..c") | "" | 範圍 a..c 含 a,b,c 全部移除 |
| 中間空白 | 不移除 | 只處理首尾,中間用 preg_replace('/\s+/', ' ', $str) |
| 全形空白 U+3000 | 預設不移除 | 需加入遮罩 trim($str, " \t\n\r\0\v\x{3000}") |
chop() vs rtrim() | 完全相同 | chop 為別名,建議用 rtrim 語意更清晰 |
效能比較
<?php
$str = str_repeat(" \t\n hello \n\t ", 10000);
$start = microtime(true);
for ($i = 0; $i < 10000; $i++) trim($str);
echo "trim: " . (microtime(true) - $start) . "s\n";
$start = microtime(true);
for ($i = 0; $i < 10000; $i++) {
// 手動實作對比
$len = strlen($str);
$startPos = 0;
$endPos = $len - 1;
while ($startPos < $len && ctype_space($str[$startPos])) $startPos++;
while ($endPos >= $startPos && ctype_space($str[$endPos])) $endPos--;
substr($str, $startPos, $endPos - $startPos + 1);
}
echo "手動: " . (microtime(true) - $start) . "s\n";
// 內建 trim 快 10 倍以上
?>
總結
trim():雙向修剪,**最常用**
ltrim():左側修剪,保留右側空白(如靠右對齊)
rtrim()/chop():右側修剪,chop 為別名建議用 rtrim
- 第 2 參數:字元遮罩(集合而非字串),支援範圍
a..z
- UTF-8 支援:PHP 7.0+ 內建函數可靠,自訂遮罩需正確編碼
- 實務模式:輸入淨化 → 正規化內部空白 → 移除控制字元