找到订单字符串中的preg_replace

时间:2016-02-12 06:43:28

标签: php preg-replace preg-match-all

我有一个短代码系统,如果在页面加载中找到一个短代码就会激活一个函数,如下所示:

[[gallery]]

问题是我需要按照找到的顺序打印短代码之间的任何文本或其他html。

[[gallery]]
This is a nice gallery

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

[[video]]
Here is a cool video!
到目前为止,我所拥有的是:

如果没有找到[[shortcodes]],不需要运行短代码功能,我们只需打印内容的正文。

           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)

所以,正如你所看到的......它复制了短代码之间的所有事件。我需要按顺序打印它们。

1 个答案:

答案 0 :(得分:0)

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

我做的事情如下:

$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!