萬盛學電腦網

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

PHP 正則表達式 preg_replace 替換入門教學:模式、回呼、修飾符、實戰範例

前言

preg_replace() 是 PHP 基於 PCRE (Perl Compatible Regular Expressions) 的強大替換函數,支援正則模式、陣列批次替換、回呼函數動態替換、修飾符控制行為。本文從基礎到進階完整解析。

基本語法

preg_replace(
    string|array $pattern,      // 正則模式或模式陣列
    string|array $replacement,  // 替換字串或替換陣列/回呼
    string|array $subject,      // 目標字串或字串陣列
    int $limit = -1,            // 最大替換次數 (-1 不限)
    int &$count = null          // 實際替換次數 (引用回傳)
): string|array|null

基礎範例

<?php
// 1. 簡單替換
echo preg_replace('/\bcat\b/i', 'dog', 'The cat and CAT'); // The dog and dog

// 2. 使用捕獲組 回參考 ($1, $2... 或 \1, \2...)
echo preg_replace('/(\d{4})-(\d{2})-(\d{2})/', '$3/$2/$1', '2024-01-15'); // 15/01/2024

// 3. 陣列模式批次替換
$patterns = ['/\s+/', '/[.,;:]/'];
$replacements = [' ', ''];
echo preg_replace($patterns, $replacements, 'Hello,  world!'); // Hello world!

// 4. 限制替換次數
echo preg_replace('/\d/', 'X', '12345', 2); // XX345 (只替換前 2 個)

// 5. 取得替換次數
$count = 0;
$result = preg_replace('/\d/', '*', 'a1b2c3', -1, $count);
echo "$result ($count)"; // a*b*c* (3)
?>

進階:回呼函數動態替換 (preg_replace_callback)

<?php
// 將所有數字乘 2
echo preg_replace_callback('/\d+/', function($m) {
    return (int)$m[0] * 2;
}, '價格 100 元,數量 5 件'); // 價格 200 元,數量 10 件

// 將 HTML 標籤轉小寫
$html = '
內容
'; echo preg_replace_callback('/<(\/?)(\w+)([^>]*)>/i', function($m) { return '<' . strtolower($m[1] . $m[2]) . $m[3] . '>'; }, $html); //
內容
// 使用箭頭函數 (PHP 7.4+) $text = 'user_123, admin_456'; echo preg_replace_callback('/(\w+)_(\d+)/', fn($m) => "{$m[1]}-ID:{$m[2]}", $text); // user-ID:123, admin-ID:456 ?>

修飾符 (Pattern Modifiers) 完整表

修飾符名稱效果
i (PCRE_CASELESS)忽略大小寫/abc/i 匹配 abc, ABC, Abc...
m (PCRE_MULTILINE)多行模式:^/$ 匹配行首/行尾/^start/m 匹配每行開頭
s (PCRE_DOTALL)單行模式:. 匹配換行符/a.b/s 匹配 a\nb
x (PCRE_EXTENDED)擴展模式:忽略空白、允許註解可寫多行註解正則
u (PCRE_UTF8)UTF-8 模式:正確處理 Unicode處理中文必加
U (PCRE_UNGREEDY)非貪婪模式:量詞預設非貪婪/.*?/U 等同 /.*?/
D (PCRE_DOLLAR_ENDONLY)$ 僅匹配字串結尾 (不匹配末尾換行前)配合 m 使用
J (PCRE_DUPNAMES)允許重複命名捕獲組(?<name>...)(?<name>...)

實戰範例集

1. 關鍵字高亮 (搜尋結果)

<?php
function highlightKeywords(string $text, array $keywords): string
{
    if (empty($keywords)) return $text;
    // 建立模式:詞界邊界、忽略大小寫、Unicode
    $pattern = '/\b(' . implode('|', array_map('preg_quote', $keywords)) . ')\b/iu';
    return preg_replace($pattern, '$1', $text);
}

echo highlightKeywords('PHP 是最好的語言', ['php', '語言']);
// PHP 是最好的語言
?>

2. 移除 HTML 標籤 (保留內容)

<?php
function stripTagsKeepContent(string $html): string
{
    // 移除標籤,保留內容
    return preg_replace('/<[^>]+>/', '', $html);
}
echo stripTagsKeepContent('

Hello World

'); // Hello World ?>

3. 將純文字 URL 自動轉為超連結

<?php
function autoLinkUrls(string $text): string
{
    // 簡易 URL 模式 (避免匹配到已是連結的)
    $pattern = '~(?])(?https?://[^\s<>"\']+)~i';
    return preg_replace($pattern, '$1', $text);
}
echo autoLinkUrls('訪問 https://example.com 了解更多');
// 訪問 https://example.com 了解更多
?>

4. 模板引擎簡易實作 (變數替換)

<?php
function renderTemplate(string $template, array $data): string
{
    return preg_replace_callback('/\{\{(\w+)\}\}/', function($m) use ($data) {
        $key = $m[1];
        return $data[$key] ?? $m[0]; // 找不到保留原樣
    }, $template);
}

$tpl = '你好,{{name}}!你的餘額:{{balance}} 元。';
echo renderTemplate($tpl, ['name' => '小明', 'balance' => 12345]);
// 你好,小明!你的餘額:12345 元。
?>

5. 防止 ReDoS (正則拒絕服務) - 避免災難性回溯

<?php
// ❌ 危險模式:嵌套量詞 + 回溯
// /^(a+)+$/ 對 'aaaaaaaaaaaaaX' 會指數級回溯

// ✅ 安全模式:佔有優先量詞 (Possessive Quantifiers) 或原子分組
// /^(a++)+$/ 或 /^(?>a+)+$/

// 實務建議:
// 1. 避免巢狀量詞 (a+)+、 (a*)*
// 2. 使用具體字元類別代替 .
// 3. 設定 preg_match 限制:ini_set('pcre.backtrack_limit', '100000');
// 4. 複雜驗證改用專用函式庫 (如 email-validator)
?>

preg_replace vs str_replace vs strtr 效能

<?php
$str = 'The quick brown fox jumps over the lazy dog. ' . str_repeat(' ', 1000);
$iterations = 100000;

$t = hrtime(true);
for ($i=0;$i<$iterations;$i++) str_replace(' ', '-', $str);
echo "str_replace: " . (hrtime(true)-$t)/1e6 . " ms\n"; // ~120 ms

$t = hrtime(true);
for ($i=0;$i<$iterations;$i++) strtr($str, ' ', '-');
echo "strtr: " . (hrtime(true)-$t)/1e6 . " ms\n"; // ~90 ms

$t = hrtime(true);
for ($i=0;$i<$iterations;$i++) preg_replace('/\s+/', '-', $str);
echo "preg_replace: " . (hrtime(true)-$t)/1e6 . " ms\n"; // ~450 ms
?>

總結

  • preg_replace 功能最強:正則模式、回呼、修飾符、陣列批次
  • 固定字串替換優先用 strtr/str_replace (快 3-5 倍)
  • 複雜替換邏輯用 preg_replace_callback (PHP 7.4+ 箭頭函數極簡潔)
  • 處理中文/Unicode 必加 u 修飾符
  • 警惕 ReDoS:避免巢狀量詞、設定 pcre.backtrack_limit、複雜驗證用專用庫
copyright © 萬盛學電腦網 all rights reserved