萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP preg_quote() 完全指南:正則表達式特殊字元轉義與分隔符處理實戰

動態構建正則表達式時,使用者輸入可能包含正則元字元 (如 . * ? [ ] ( ) 等),直接拼接會導致模式錯誤或安全漏洞。preg_quote() 是 PHP 官方提供的唯一標準轉義函式,本文詳細解析其參數、行為邊界、效能特性與實戰應用模式。

函式簽名與參數詳解

preg_quote(string $string, ?string $delimiter = null): string
  • $string:需轉義的原始字串
  • $delimiter:可選,指定正則分隔符 (如 /, #, ~),若提供則同時轉義該字元,避免分隔符衝突
  • 返回:已轉義的字串,所有 PCRE 特殊字元前加上反斜線

PCRE 特殊字元完整列表 (會被轉義)

. \ + * ? [ ^ ] $ ( ) { } = ! < > | : -

注意:# @ % ! 等非標準元字元不會被轉義,除非作為 $delimiter 指定。

核心範例與行為驗證

<?php
$input = '$40 for a g3/400';

// 無分隔符:僅轉義正則元字元
echo preg_quote($input); 
// 輸出: \$40 for a g3\/400  (注意 $ 和 / 都被轉義)

// 指定分隔符 '/'
echo preg_quote($input, '/'); 
// 輸出: \$40 for a g3\/400  (相同,因 / 已是元字元)

// 指定分隔符 '#'
echo preg_quote($input, '#'); 
// 輸出: \$40 for a g3/400  (# 未在字串中,/ 不再被轉義)

// 實際構建模式
$keyword = 'user[name]';
$pattern = '/^' . preg_quote($keyword, '/') . '$/'; // 產生 /^user\[name\]$/
// 可安全匹配字面字串 "user[name]"

實戰應用場景

1. 搜尋關鍵字高亮 (防止 XSS/ReDoS)

function highlightKeywords(string $text, array $keywords): string {
    // 1. 轉義所有關鍵字
    $escaped = array_map(fn($kw) => preg_quote($kw, '/'), $keywords);
    // 2. 組合成單一模式 (使用單字邊界 \b 避免部分匹配)
    $pattern = '/\b(' . implode('|', $escaped) . ')\b/iu';
    // 3. 替換為高亮標籤
    return preg_replace($pattern, '$0', $text);
}

$text = "PHP 的 preg_quote() 函數用於轉義正則特殊字元。";
$keywords = ['preg_quote()', '正則', 'PHP'];
echo highlightKeywords($text, $keywords);
// 輸出: PHP 的 preg_quote() 函數用於轉義正則特殊字元。

2. 安全構建路由匹配模式

function buildRoutePattern(string $route): string {
    // 路由參數語法: /user/{id:\d+}/post/{slug}
    // 靜態部分需轉義,參數部分保留正則
    $segments = explode('/', trim($route, '/'));
    $patternSegments = [];
    foreach ($segments as $seg) {
        if (preg_match('/^\{(.+?)(?::(.+?))?\}$/', $seg, $m)) {
            // 參數段: {name} 或 {name:pattern}
            $name = $m[1];
            $regex = $m[2] ?? '[^/]+';
            $patternSegments[] = "(?P<$name>$regex)";
        } else {
            // 靜態段: 必須轉義
            $patternSegments[] = preg_quote($seg, '/');
        }
    }
    return '#^/' . implode('/', $patternSegments) . '$#';
}

$pattern = buildRoutePattern('/api/user/{id:\d+}/profile');
// 結果: #^/api/user/(?P\d+)/profile$#

3. 字串替換中的字面替換 (非正則)

function strReplaceLiteral(string $search, string $replace, string $subject): string {
    // 將 $search 視為字面字串而非正則
    return preg_replace('/' . preg_quote($search, '/') . '/', $replace, $subject);
}

// 對比
$subject = 'Price: $100 and $200';
echo strReplaceLiteral('$100', 'USD 100', $subject); // Price: USD 100 and $200
// 直接用 preg_replace('$100', ...) 會匹配行尾錨點 ^

效能考量與替代方案

常見錯誤與避坑

  • 忘記轉義分隔符:模式 /.../ 中搜尋字串含 / 必須 preg_quote($str, '/')
  • 雙重轉義:已轉義字串再次傳入 preg_quote() 導致反斜線疊加
  • Unicode 字元:preg_quote() 僅處理 ASCII 元字元,Unicode 字元 (如全形括號) 不轉義,但 PCRE 視為字面字元,通常無害
  • NULL 位元組:PHP 字串可含 \0,PCRE 視為字串結束,需自行處理

結語

preg_quote() 是構建動態正則的安全閥。鐵律:任何來自外部輸入 (用戶、配置、資料庫) 的字串,拼入正則模式前必須經過 preg_quote($str, $delimiter)。配合 preg_match_all() 批次匹配、預編譯模式快取,即能在安全與效能間取得平衡。

copyright © 萬盛學電腦網 all rights reserved
場景推薦做法理由
固定字串搜尋/替換strpos() / str_replace()O(n) 線性掃描,無正則引擎開銷,快 10-100 倍
動態關鍵字、需正則特性 (邊界、量詞)preg_quote() + preg_match/replace正確性優先,效能次之
超大字串 (MB 級) 多次搜尋預編譯模式 + preg_match_all()避免重複編譯正則
固定前綴/後綴匹配str_starts_with() / str_ends_with() (PHP 8+)原生函式最快