Example #1 preg_replace_callback() 和 匿名函数
<?php
/* 一个unix样式的命令行过滤器,用于将段落开始部分的大写字母转换为小写。 */
$fp = fopen("php://stdin", "r") or die("can't read stdin");
while (!feof($fp)) {
$line = fgets($fp);
$line = preg_replace_callback(
'|<p>\s*\w|',
function ($matches) {
return strtolower($matches[0]);
},
$line
);
echo $line;
}
fclose($fp);
?>
Example #2 preg_replace_callback()示例
<?php
// 将文本中的年份增加一年.
$text = "April fools day is 04/01/2002\n";
$text.= "Last christmas was 12/24/2001\n";
// 回调函数
function next_year($matches)
{
// 通常: $matches[0]是完成的匹配
// $matches[1]是第一个捕获子组的匹配
// 以此类推
return $matches[1].($matches[2]+1);
}
echo preg_replace_callback(
"|(\d{2}/\d{2}/)(\d{4})|",
"next_year",
$text);
?>
Example #3 preg_replace_callback()使用递归构造处理BB码的封装
<?php
$input = "plain [indent] deep [indent] deeper [/indent] deep [/indent] plain";
function parseTagsRecursive($input)
{
/* 译注: 对此正则表达式分段分析
* 首尾两个#是正则分隔符
* \[indent] 匹配一个原文的[indent]
* ((?:[^[]|\[(?!/?indent])|(?R))+)分析:
* (?:[^[]|\[(?!/?indent])分析:
* 首先它是一个非捕获子组
* 两个可选路径, 一个是非[字符, 另一个是[字符但后面紧跟着不是/indent或indent.
* (?R) 正则表达式递归
* \[/indent] 匹配结束的[/indent]
* /
$regex = '#\[indent]((?:[^[]|\[(?!/?indent])|(?R))+)\[/indent]#';
if (is_array($input)) {
$input = '<div style="margin-left: 10px">'.$input[1].'</div>';
}
return preg_replace_callback($regex, 'parseTagsRecursive', $input);
}
$output = parseTagsRecursive($input);
echo $output;
?>