在preg_replace_callback在replaceContent(
问题描述:
function replaceContent($matches = array()){
if ($matches[1] == "nlist"){
// do stuff
return "replace value";
} elseif ($matches[1] == "alist"){
// do stuff
return "replace value";
}
return false;
}
preg_replace_callback('/<([n|a]list)\b[^>]*>(.*?)<\/[n|a]list>/','replaceContent', $page_content);
$匹配)改变替换值,如果发现匹配返回这个数组:在preg_replace_callback在replaceContent(
Array
(
[0] => <nlist>#NEWSLIST#</nlist>
[1] => nlist
[2] => #NEWSLIST#
)
Array
(
[0] => <alist>#ACTIVITYLIST#</alist>
[1] => alist
[2] => #ACTIVITYLIST#
)
此刻我preg_replace_callback函数$替换匹配值匹配[0]。我想要做的,想知道如果甚至可能的话,就是替换标签内的所有东西($ matches [2]),同时可以执行$ matches [1]检查。
测试我正则表达式在这里:http://rubular.com/r/k094nulVd5
答
你可以简单地调整返回值,包括您不零件要更换不变:
function replaceContent($matches = array()){
if ($matches[1] == "nlist"){
// do stuff
return sprintf('<%s>%s</%s>',
$matches[1],
'replace value',
$matches[1]);
} elseif ($matches[1] == "alist"){
// do stuff
return sprintf('<%s>%s</%s>',
$matches[1],
'replace value',
$matches[1]);
}
return false;
}
preg_replace_callback('/<([n|a]list)\b[^>]*>(.*?)<\/[n|a]list>/','replaceContent', $page_content);
需要注意的是:
-
sprintf
内部的模式是基于preg_replace_callback
所使用的正则表达式生成的。 - 如果替换字符串需要包含原始信息(例如
<nlist>
或<alist>
标记中的可能属性),则还需要将这些数据存入捕获组中,以便在$matches
内可用。