2016-11-29 226 views
0

你好,我有以下代碼:PHP爲什麼preg_match沒有工作?

$headerOcc = substr_count($text, "[Image]["); 

    if($headerOcc < '1'){ 
    $text = $text; 
    } 


    for ($i=0; $i < $headerOcc; $i++) {  
     preg_match('/[Image\]\[(.*)\]/', $text, $match); 
     $headerTitle = ($match[1]);   
     print($headerTitle);  
    } 

我也有以下變化:

$text = "Hello world [Image][61][Image][62]Hello world"; 

我想找出是否有是說[圖片]​​ [ID文本的一部分]。顯然,ID將被一個數字取代,我想得到它。我如何獲得$ headerTitle在大括號內返回該ID。目前,它給了我這個當我打印:

61]** 

** [圖片] [62

這是不是我想要的。我想要它回來:

61 

62 

我在做什麼錯,我該如何解決它?

+0

在'$ text'中使用大括號'{}',但在模式中查找括號'[]'。 – AbraCadaver

+0

這就是我的錯誤不是一個真正的錯誤抱歉。我修好了 – Jelly

回答

0

使用preg_match_all()和使用\d+獲得數字:

preg_match_all('/\[Image\]\[(\d+)\]/', $text, $matches); 

或者你可以匹配不],所以([^\]]+)

然後就循環$matches[1]呼應等等

foreach($matches[1] as $headerTitle) { 
    print($headerTitle); 
} 

無需爲substr_count()或任何其他的東西。

+0

謝謝!有效! – Jelly

相關問題