在 preg_replace()、ereg_replace() 等替換函數的 replacement 參數中,可使用以下特殊符號引用匹配內容:
| 符號 | 名稱 | 說明 | 範例 |
|---|---|---|---|
$1 ~ $999 | 編號捕獲組 | 引用第 N 個 (...) 捕獲內容。超過最大組號時,DEELX 會截斷數字(如 $999 → $9 + "99")。 | preg_replace('/(\d{4})-(\d{2})/', '$2/$1', '2024-03') → '03/2024' |
${name} | 具名捕獲組 | 引用 (?<name>...) 捕獲內容(PHP 5.2.2+)。 | preg_replace('/(?<y>\d{4})-(?<m>\d{2})/', '${m}/${y}', '2024-03') → '03/2024' |
$$ | 字面 $ 符號 | 輸出實際 $ 字符。 | preg_replace('/\$/', '$$', '$100') → '$$100' |
$& | 整個匹配 | 完整匹配到的子串($0 同義)。 | preg_replace('/\d+/', '[$&]', 'a123b') → 'a[123]b' |
$` | 匹配前文本 | 匹配位置之前的所有字符(反引號 `)。 | preg_replace('/\d+/', '$`', 'ab12cd') → 'ababcd' |
$' | 匹配後文本 | 匹配位置之後的所有字符(單引號 ')。 | preg_replace('/\d+/', "$'", 'ab12cd') → 'abcdcd' |
$+ | 最後捕獲組 | 所有有捕獲內容的組中編號最大者(非單純最大編號)。 | preg_replace('/(a)|(b)/', '$+', 'a') → 'a';匹配 'b' → 'b' |
$_ | 整個被替換字串 | 原始完整字串(下劃線 _)。 | preg_replace('/\d+/', '$_', 'a12b') → 'aa12bb' |
preg_replace 僅支援 $0/$1~$99、${name}。$&、$`、$'、$+、$_ 屬於 DEELX/RegexBuddy/JS/Perl 擴展語法,PHP 不支援。preg_replace_callback 實現上述高級功能。function advanced_replace($pattern, $subject) {
return preg_replace_callback($pattern, function($m) use ($subject) {
$repl = '$1'; // 假設替換模板來自配置
$repl = str_replace('$&', $m[0], $repl);
$repl = str_replace('$`', substr($subject, 0, $m[0][1] ?? 0), $repl); // 需 PREG_OFFSET_CAPTURE
$repl = str_replace("$'", substr($subject, $m[0][1] + strlen($m[0])), $repl);
$repl = str_replace('$+', end(array_filter($m, 'is_string', ARRAY_FILTER_USE_KEY)), $repl);
$repl = str_replace('$_', $subject, $repl);
return $repl;
}, $subject);
}
${name} 具名捕獲,可讀性高、不易因組數變動出錯。preg_replace_callback,在 PHP 回調中自由處理。$ 符號防止注入。