preg_replace_callback() 是 PHP 正則替換的利器:將匹配內容傳遞給回調函數處理,返回替換結果。適用於複雜替換邏輯(如條件判斷、動態計算、多階段轉換)。
preg_replace_callback(
string|array $pattern,
callable $callback,
string|array $subject,
int $limit = -1,
int &$count = null
): string|array
<?php
$Text = "Title: Hello world!\n";
$Text .= "Author: Jonas\n";
$Text .= "This is a example message!\n\n";
$Text .= "Title: Entry 2\n";
$Text .= "Author: Sonja\n";
$Text .= "Hello world, what's up!\n";
// 回調函數:將 "Key: Value" 轉為 "Key: Value"
function RewriteText($matches) {
$key = $matches[1]; // ([a-z0-9]+)
$value = $matches[2]; // ([^\n\r]+)
return '<b>' . $key . '</b>: ' . $value;
}
// 正則:匹配換行開頭的 "Key: Value"
$pattern = '/[\r\n]([a-z0-9]+): ([^\n\r]+)/i';
$NewText = preg_replace_callback($pattern, "RewriteText", $Text);
echo $NewText;
/* 輸出:
<b>Title</b>: Hello world!
<b>Author</b>: Jonas
...
*/
$matches[0]:完整匹配的字符串(含換行符)。$matches[1], $matches[2]...:捕獲組內容。fn($m) => ...。$matches[0] 表示不替換)。&$count 統計實際替換次數。$limit 參數控制最大替換次數。preg_replace 更快;僅在邏輯複雜時用 callback。/i 忽略大小寫導致匹配失敗。[^\n\r]+ 而非 .*。掌握 preg_replace_callback,讓正則替換從「死板」變「靈活」。