php正则中有一个回调函数,本函数的行为几乎和 preg_replace() 一样,除了不是提供一个 replacement 参数,而是指定一个 callback 函数。该函数将以目标字符串中的匹配数组作为输入参数,并返回用于替换的字符串。
也就是说mixed preg_replace_callback ( mixed pattern, callback callback, mixed subject [, int limit] )中
第二参数可以调用一个函数,函数的参数是其中的正则做为参数
以下是一个正则回调函数的例子
目的:给一组你要匹配的词语。当在文本中出现你想要匹配的词语,给这些词加上链接。
function preg_callback_func($matches){
return "{$matches[0]}";
}
$keyword="php函数|php采集|正则表达式|php源码";
$text="If you're using preg_replace() on huge strings you have to be aware php函数of PREG's limitations. In fact, after each preg_xxx() function you should check if PREG internally failed (and by\"failure\" I don't meanphp采集 regexp syntax errors).On default PHP installations you will run into 我们problems when using preg_xxx() functionsphp源码 on strings with a length of more than 100'000 characters. To workaround rare occasions you can use this:";
echo preg_replace_callback("/$keyword/","preg_callback_func",$text);
?>
以上输出结果是 $keyword 中词语都被加上链接
preg_replace_callback("/$keyword/","preg_callback_func",$text);
“preg_callback_func 即是你要调的函数”函数侜是给关键字加入标签
“php函数|php采集|正则表达式|php源码” 是你要匹配文本