preg_replace 找到顺序字符串

preg_replace in order string is found

我有一个短代码系统,如果在页面加载时发现短代码,它会触发一个函数,如下所示:

[[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 var 的顺序显示它们。即使我将 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)

因此,如您所见.. 它复制了短代码之间的所有匹配项。我需要按顺序打印它们。

在为每个短代码调用 shortcodify 之前,您正在打印整个 $page_text

我会这样做:

$page_content = <<<EOD
[[gallery]]
This is a nice gallery

[[blog id=1]]
This is a recent blog

[[video]]
Here is a cool video!

EOD;

if(preg_match('#\[\[(.*?)\]\]#', $page_content)){ // there are shortcodes
    $items = explode("\n", $page_content);        // split on line break --> array of lines
    foreach($items as $item) {    // for each line
        if(preg_match('#\[\[(.*?)\]\]#', $item)){  // there is a shortcode in this line
            // replace shortcode by the resulting value
            $item = preg_replace_callback('#\[\[(.*?)\]\]#', 
                        function ($m) {
                             shortcodify($m[1]);
                        },
                        $item);
        }
        // print the current line
        print "$item\n";
    }
} else {    // there are no shortcodes
    print $page_content;
}

function shortcodify($theFunction) {
    print "running $theFunction";
}

输出:

running gallery
This is a nice gallery

running blog id=1
This is a recent blog

running video
Here is a cool video!