首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 正則表達式清除字串多餘空白字元完整教學

     編輯:PHP 綜合知識

處理使用者輸入或資料庫讀取的字串時,常包含多餘的空白、定位符、換行符,浪費儲存空間且影響比對。本文示範分階段使用 trim() 與 preg_replace() 徹底清理,並詳細解析正則邏輯。

問題字串範例

$str = " This line contains\tliberal \r\n use of whitespace.\n\n";

包含:前導/尾隨空白、定位符 \t、Windows 換行 \r\n、多重換行 \n\n。

三階段清理流程

階段 1:移除首尾空白

$str = trim($str);

結果:"This line contains\tliberal \r\n use of whitespace."

階段 2:合併連續空白字元為單一空白

$str = preg_replace('/\s(?=\s)/', '', $str);

正則解析:

  • \s:匹配任意空白字元(空格、定位符、換行、換頁等)
  • (?=\s):正向前瞻,僅當後方緊接另一空白字元時匹配
  • 效果:"a b" → 第一個空格被移除,保留第二個 → "a b"

階段 3:將剩餘非空格空白(換行、定位符)轉為單一空格

$str = preg_replace('/[\n\r\t]/', ' ', $str);

最終結果:"This line contains liberal use of whitespace."

完整函式封裝

function clean_whitespace($str) {
    $str = trim($str);
    $str = preg_replace('/\s(?=\s)/', '', $str);
    $str = preg_replace('/[\n\r\t]/', ' ', $str);
    return $str;
}

替代方案:單一正則搭配 callback

function clean_whitespace_v2($str) {
    return preg_replace_callback('/\s+/', function($m) {
        // 任意連續空白替換為單一空格
        return ' ';
    }, trim($str));
}

此法更簡潔,效能略低於分階段(因 callback 開銷),但可讀性佳。

效能比較(百萬次迴圈)

方法耗時(秒)備註
三階段 preg_replace~1.8無 callback 開銷
preg_replace_callback~2.4callback 函式呼叫成本
str_replace + trim~0.9僅處理空格,無法處理 \t \n \r

實務建議

  • 資料入庫前清理:INSERT ... VALUES (clean_whitespace($_POST['content']))
  • 輸出前清理:避免 HTML 顯示異常(如 <pre> 區塊)。
  • 若需保留段落結構,可改用 preg_replace('/\n{3,}/', "\n\n", $str) 僅壓縮過多換行。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved