在 PHP 開發中,處理字串中的空白字元(空格、換行符、回車符)是常見需求。本文整理了三種核心場景的解決方案,並提供可直接套用的程式碼範例。
以下範例展示如何分步驟清理字串:先去除首尾空白,再壓縮連續空白,最後統一將特殊空白字元替換為單一空格。
<?php
$str = " This line containstliberal rn use of whitespace.nn";
// 1. 去除首尾空白
$str = trim($str);
// 2. 移除連續的空白字元(僅保留第一個)
$str = preg_replace('/\s(?=\s)/', '', $str);
// 3. 將換行、製表、回車替換為單一空格
$str = preg_replace('/[\n\r\t]/', ' ', $str);
echo "<pre>{$str}</pre>";
// 輸出:This line contains liberal use of whitespace.
?>
關鍵點解析:
trim():標準函式,移除字串首尾的空白字元(含 \n, \r, \t, \0, \x0B)preg_replace('/\s(?=\s)/', '', $str):使用正向前瞻,僅刪除後方緊接空白字元的字元,達到壓縮連續空白的效果preg_replace('/[\n\r\t]/', ' ', $str):將常見控制字元統一轉為空格,便於前端顯示根據效能與可攜性考量,推薦優先使用內建常數 PHP_EOL。
$str = str_replace(["\r\n", "\r", "\n"], '', $str);
$str = preg_replace('/\s*/', '', $str);
$str = str_replace(PHP_EOL, '', $str);
補充說明: PHP_EOL 會根據執行環境自動對應正確的換行符(Windows: \r\n, Linux/Unix: \n, 旧版 Mac: \r),避免硬編碼導致的相容性問題。
若需在伺服器端根據客戶端 UA 判斷換行格式,可參考以下函式:
function get_crlf() {
$ua = $_SERVER['HTTP_USER_AGENT'] ?? '';
if (stripos($ua, 'Win') !== false) {
return "\r\n";
} elseif (stripos($ua, 'Mac') !== false) {
return "\r"; // 旧版 Mac OS
} else {
return "\n"; // Linux/Unix/現代 macOS
}
}
將資料庫存儲的換行符轉為 HTML <br> 標籤以便網頁正確換行:
echo nl2br($content);
同樣提供三種方式,建議統一使用 PHP_EOL 或 str_replace 陣列寫法:
<?php
// 不同系統換行符差異說明
// Linux/Unix: \n
// 旧版 Mac: \r
// Windows: \r\n
// 方式 1:陣列替換(明確、可控)
$str = str_replace(["\r\n", "\r", "\n"], '', $str);
// 方式 2:正則替換
$str = preg_replace('/\s*/', '', $str);
// 方式 3:PHP_EOL(最佳實踐)
$str = str_replace(PHP_EOL, '', $str);
?>
trim() + str_replace(PHP_EOL, ' ', $str)PHP_EOL 而非硬編碼換行符nl2br() 或 CSS white-space: pre-wrap 處理換行顯示str_replace 效能優於 preg_replace