【发布时间】:2016-02-12 06:43:27
【问题描述】:
我有一个短代码系统,如果在页面加载时发现短代码,它将触发一个函数,如下所示:
[[gallery]]
问题是我需要按找到的顺序打印在短代码之间找到的任何文本或其他 html。
[[gallery]]
This is a nice gallery
[[blog id=1]]
This is a recent blog
[[video]]
Here is a cool video!
我目前的情况是这样的:
如果没有找到[[shortcodes]],则不需要运行shortcode函数,我们只打印内容的正文。
if(!preg_match('#\[\[(.*?)\]\]#', $page_content, $m1)){
print $page_content;
}
这将删除所有短代码并打印文本,但仅将其打印在找到的所有短代码之上。
if(preg_match('#\[\[(.*?)\]\]#', $page_content, $m1)){
$theFunction1 = $m1[0];
$page_text = preg_replace('#\[\[(.*?)\]\]#', '',$page_content);
print $page_text;
}
如果我们找到任何 [[shortcodes]],我们会遍历它们并将它们传递给一个函数以通过回调来处理它们。
if(preg_match_all('#\[\[(.*?)\]\]#', $page_content, $m)){
foreach($m[0] as $theFunction){
print shortcodify($theFunction);
}
}
preg_replace 不按 $page_content 变量的顺序显示它们,因为它们被发现。即使我将 preg_replace 放在 foreach 循环中,我也会得到如下结果:
This is a nice gallery
This is a recent blog
This is a recent blog
[[gallery]] (gallery loads)
This is a nice gallery
This is a recent blog
This is a recent blog
[[blog id=1]] (the blog displays)
This is a nice gallery
This is a recent blog
This is a recent blog
[[video]] (video plays)
所以,如您所见.. 它复制了短代码之间的所有匹配项。我需要按顺序打印它们。
【问题讨论】:
标签: php preg-replace preg-match-all