一般 trim() 僅移除 ASCII 空白字元,無法處理 (U+00A0 不換行空白)或全形空白(U+3000)。本文提供兩種健壯解法:正則表達式與 html_entity_decode 配合 trim。
<?php
function trimAll(string $str): string {
// 移除字串首尾的所有 Unicode 空白字元(含 、全形空白、零寬空白等)
return preg_replace('/^[\s\p{Z}]+|[\s\p{Z}]+$/u', '', $str);
}
$test = " \xC2\xA0 dfadad 論責民與三英的關系775fd \xC2\xA0 ";
var_dump(trimAll($test));
// string(35) "dfadad 論責民與三英的關系775fd"
?>
\s 匹配 ASCII 空白,\p{Z} 匹配所有 Unicode 分隔符號(Zs, Zl, Zp),u 修飾符啟用 UTF-8 模式。
<?php
function trimNbsp(string $str): string {
// 1. 將 HTML 實體 解碼為實際字元 (U+00A0)
// 2. trim 移除該字元(需以 UTF-8 位元組序列指定)
$decoded = html_entity_decode($str, ENT_QUOTES, 'UTF-8');
return trim($decoded, "\xC2\xA0"); // U+00A0 的 UTF-8 編碼
}
$test = " \xC2\xA0 dfadad 3333adf775fd \xC2\xA0 ";
var_dump(trimNbsp($test));
// string(19) "dfadad 3333adf775fd"
?>
html_entity_decode 在非 UTF-8 環境下會產生亂碼,且 json_encode 會將非 UTF-8 中文轉為 null。| 方法 | 適用編碼 | 處理範圍 | 相對速度 |
|---|---|---|---|
| preg_replace (Unicode) | UTF-8 | 所有 Unicode 空白 | 中等 |
| html_entity_decode + trim | UTF-8 | 及 ASCII 空白 | 快 |
| trim() 內建 | 所有 | ASCII 空白のみ | 最快 |