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
// 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/'; 避免重复编译。