【问题标题】:preg_replace in order string is foundpreg_replace 在 order 字符串中找到
【发布时间】: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


    【解决方案1】:

    在为每个短代码调用 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!
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-28
      • 1970-01-01
      • 1970-01-01
      • 2011-01-29
      • 2023-01-26
      • 2013-09-02
      • 1970-01-01
      相关资源
      最近更新 更多