更改 preg_replace_callback 中的替换值
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);
如果找到匹配项,replaceContent() 中的 $matches 将返回此数组:
Array
(
[0] => <nlist>#NEWSLIST#</nlist>
[1] => nlist
[2] => #NEWSLIST#
)
Array
(
[0] => <alist>#ACTIVITYLIST#</alist>
[1] => alist
[2] => #ACTIVITYLIST#
)
目前,我的 preg_replace_callback 函数将匹配值替换为 $matches[0]。我想要做的并且想知道是否可能是替换标签内的所有内容($matches[2]),同时能够进行 $matches[1] 检查。
在这里测试我的正则表达式: http://rubular.com/r/k094nulVd5
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);
$matches in replaceContent() returns this array if matches are found:
Array
(
[0] => <nlist>#NEWSLIST#</nlist>
[1] => nlist
[2] => #NEWSLIST#
)
Array
(
[0] => <alist>#ACTIVITYLIST#</alist>
[1] => alist
[2] => #ACTIVITYLIST#
)
At the moment my preg_replace_callback function replaces the matches value with $matches[0]. What I am trying to do and wondering if even possible is to replace everything inside the tags ($matches[2]) and at the same time be able to do the $matches[1] check.
Test my regex here: http://rubular.com/r/k094nulVd5
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以简单地调整返回值以包含您不想想要原样替换的部分:
请注意:
sprintf
中的模式是根据用于的正则表达式生成的preg_replace_callback
。
或
标记中可能的属性),您将需要获取此信息数据也放入捕获组中,以便它在$matches
中可用。You can simply adjust the return value to include the parts that you don't want to replace unchanged:
Note that:
sprintf
is produced based on the regex used forpreg_replace_callback
.<nlist>
or<alist>
tags), you will need to get this data into a capture group as well so that it's available inside$matches
.