萬盛學電腦網

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

PHP preg_replace_callback 详解:正则替换回调实现动态模板渲染

函数原型

mixed preg_replace_callback ( mixed $pattern , callable $callback , mixed $subject [, int $limit = -1 [, int &$count ]] )

每次匹配到 $pattern,将匹配数组传给 $callback,回调返回值作为替换结果。

实战示例:键值对高亮

<?php
$text = "Title: Hello world!\nAuthor: Jonas\n\nTitle: Entry 2\nAuthor: Sonja\nHello world!";

function highlightKey($matches) {
    // $matches[0] 整个匹配 "Title: Hello world!"
    // $matches[1] 第一捕获组 "Title"
    // $matches[2] 第二捕获组 "Hello world!"
    return '<b>' . htmlspecialchars($matches[1]) . '</b>: ' . htmlspecialchars($matches[2]);
}

$pattern = '/\n([a-z0-9]+): ([^\n\r]+)/i';
$newText = preg_replace_callback($pattern, 'highlightKey', $text);
echo $newText;
/* 输出:
<b>Title</b>: Hello world!
<b>Author</b>: Jonas

<b>Title</b>: Entry 2
<b>Author</b>: Sonja
Hello world!
*/

进阶:匿名函数闭包捕获外部变量

$replacements = array('foo'=>'bar', 'baz'=>'qux');
$text = 'foo and baz';

$newText = preg_replace_callback('/\b(\w+)\b/', function($m) use ($replacements) {
    return isset($replacements[$m[1]]) ? $replacements[$m[1]] : $m[0];
}, $text);
echo $newText; // bar and qux

对比:preg_replace /e 修饰符(已移除)


// PHP 5.5 废弃,7.0 移除
// $new = preg_replace('/(\w+)/e', 'strtoupper("$1")', $text); // 危险:代码注入风险

// 迁移到 callback
$new = preg_replace_callback('/(\w+)/', function($m) { return strtoupper($m[1]); }, $text);

性能提示

  • 回调函数频繁调用开销大,简单替换优先用 preg_replace 纯字符串/数组替换。
  • 复杂逻辑在回调外预编译正则 $re = '/pattern/'; 避免重复编译。
  • 大文本分块处理,避免单次正则回溯过深导致超时。
copyright © 萬盛學電腦網 all rights reserved