2016-02-12 18 views
0

我有一個簡碼系統,該系統將觸發一個功能,如果一個短代碼在頁面加載時發現,像這樣:的preg_replace發現

[[gallery]] 

問題是,我需要打印發現的任何文本或其他HTML按照它們被發現的順序在短代碼之間。

[[gallery]] 
This is a nice gallery 

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

[[video]] 
Here is a cool video! 

什麼我到目前爲止是這樣的:

如果沒有[簡碼]發現,無需運行簡碼的功能,我們只打印內容的主體。

  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; 
      } 

如果我們發現任何[簡碼],我們環通它們,並將它們傳遞給一個函數與一個回調來處理它們。

  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) 

所以,你可以看到..它複製所有的簡碼的出現。我需要按順序打印它們。

回答

0

在爲每個簡碼調用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! 
+0

謝謝!它完美的作品! –

+0

@SonnyKing:不客氣,很高興幫助。 – Toto