2010-06-25 18 views
0

我們使用自定義設置高亮在我們的新聞帖子使用的preg_match獲得的文件名

[newsImage] imageName.jpg [/ newsImage]

,我想使用的preg_match從之間獲得imageName.jpg這些標籤。整篇文章存儲在一個名爲$ newsPost的變量中。

我是新的正則表達式,我只是無法弄清楚的preg_match用得到我想要什麼合適的表情。

任何幫助表示讚賞。另外,你們中的任何一個人都知道一個很好的資源來學習正則表達式中每個字符的用法嗎?

回答

2
preg_match_all('/\[newsImage\]([^\[]+)\[\/newsImage\]/i', $newsPost, $images); 

變量$images應該再包含您的匹配列表。

http://www.php.net/manual/en/regexp.introduction.php

+0

因爲我只是想匹配的第一個實例,我只使用的preg_match,並告訴我,$圖像是一個數組。所以我嘗試了$圖片[1]和$圖片[0],但我得到0結果兩個。 – Andelas 2010-06-25 16:51:28

+1

修復了最後一個支架! 'preg_match' *應該*返回你的圖像名稱爲$ images [1]或'false',如果沒有任何匹配。 – Rob 2010-06-25 18:29:13

+0

謝謝。我不完全確定爲什麼,但那仍然不適合我。我能夠使用這個/\[[/snewsImage](.*?)\[[//newsImage\]/is – Andelas 2010-06-25 20:54:35

0

這不正是你問什麼,但你可以用下面的代碼標記替代你的[newsImage]標籤,它不是完美的,因爲它會掉下來,如果你有一個空的標籤如[newsImage] [/ newsImage]

function process_image_code($text) { 
     //regex looks for [newsImage]sometext[/newsImage] 
     $urlReg ="/((?:\[newsImage]{1}){1}.{1,}?(?:\[\/newsImage]){1})/i"; 
     $pregResults = preg_split ($urlReg , $text, -1, PREG_SPLIT_DELIM_CAPTURE); 
     $output = ""; 

     //loop array to build the output string 
     for($i = 0; $i < sizeof($pregResults); $i++) { 

      //if the array item has a regex match process the result 
      if(preg_match($urlReg, $pregResults[$i])) { 
       $pregResults[$i] = preg_replace ("/(?:\[\/newsImage]){1}/i","\" alt=\"Image\" border=\"0\" />",$pregResults[$i] ,1); 

       // find if it has a http:// at the start of the image url 
       if(preg_match("/(?:\[newsImage]http:\/\/?){1}/i",$pregResults[$i])) { 
        $pregResults[$i] = preg_replace ("/(?:\[newsImage]?){1}/i","<img src=\"",$pregResults[$i] ,1); 
       }else { 
        $pregResults[$i] = preg_replace ("/(?:\[newsImage]?){1}/i","<img src=\"http://",$pregResults[$i] ,1); 
       } 

       $output .= $pregResults[$i]; 
      }else { 
       $output .= $pregResults[$i]; 
      } 
     } 

     return $output; 
    } 
1

正如羅布說,但最後逃避]

preg_match('/\[newsImage\]([^\[]+)\[newsImage\]/i', $newsPost, $images); 

$圖像[1]將包含圖像文件的名稱。