2013-03-22 28 views
1

我一直在試圖完成這個幾天。我在每個帖子中都有一個描述,它們將佔位符手動放置在我想要替換相應圖像的地方。例如:

This is the description shortened... 
[image] 
[image] 
Description starts again with a new paragraph continuing... 

佔位符是[image]。隨着每個新帖子上傳多張圖片,每張帖子可能會與1-10張圖片有所不同,因此會放置不定數量的[圖片]佔位符。我有一個功能,可以將所有相關圖像傳送到該帖子並計算出有多少圖像。

這是我到目前爲止的代碼,但是最後兩個佔位符[image]它顯示第一個相關圖像兩次,然後循環並再次顯示描述,這次用第二個圖像替換兩個[圖片]佔位符。

<?php 
    foreach ($photos as $picture) { 
    $count = count($picture); 
    for($i = 1; $i<= $count; $i++) { 
     $image = $picture['filename']; 
     $replace = "[image]"; 
     $image_path = '../../content_management/image_upload/'; 
     $placeholders = array("$replace"); 
     $image_location = array('<a class="fancybox" href="' . $image_path . '' . $image . '" data-fancybox-group="gallery"><img src="' . $image_path . '' . $image . '" /></a>'); 
     $rawstring = $photo_article['description']; 
     $new_string = $rawstring; 
     $new_string = str_replace($placeholders, $image_location, $new_string, $i); 
     echo $new_string; 
    } 
    } 
?> 

什麼輸出結果是:你循環

This is the description shortened... 
Image1.jpg 
Image1.jpg 
Description starts again with a new paragraph continuing... 

This is the description shortened... 
Image2.jpg 
Image2.jpg 
Description starts again with a new paragraph continuing... 
+0

你的問題很可能是'$ I '在str_replace調用中,應該是1.但是使用'str_replace'無論如何是笨拙的。考慮'preg_replace_callback'。 – mario 2013-03-22 02:18:30

+0

如果我將$ i從str_replace()中取出;它現在使輸出翻倍。我會嘗試使用preg_replace_callback – tunedin 2013-03-22 02:26:35

回答

0
$photos = array(
    'photo1' => array(
    'filename' => 'image1.png' 
    ), 
    'photo2' => array(
    'filename' => 'image2.png' 
    ), 
); 

$photo_article['description'] = "This is the description shortened... 
[image] 
[image]"; 

foreach ($photos as $picture) 
{ 
    $image = $picture['filename']; 
    $image_path = '../../content_management/image_upload/'; 
    $replacement = '<a class="fancybox" href="' . $image_path . '' . $image . '" data-fancybox-group="gallery"><img src="' . $image_path . '' . $image . '" /></a>'; 
    $photo_article['description'] = preg_replace("~\[image\]~s", $replacement, $photo_article['description'], 1); 
} 
    echo $photo_article['description']; 
+0

我試圖應用你的代碼,但現在它只是用[image]佔位符迴響每個描述兩次。這不是取代他們.. – tunedin 2013-03-22 02:47:58

+0

我編輯了我的答案。我已經包含了我用來測試它的$ photos數組和$ photo_article變量。 – C9HDN 2013-03-22 03:08:32

+0

而不是定義文章中的圖像,然後preg_replacing ...爲什麼不只是將圖像追加到像$ foreach($照片爲$圖片)$ ... photo_article ['description']。= $更換; } – 2013-03-22 03:10:53

0

但調用相同$picture['filename']應該$picture[$i]['filename']或只是foreach ($picture as $thisPic) { $thisPic['filename']; }

+0

我不認爲你可以做$ picture [$ i] ['filename']; – tunedin 2013-03-22 02:45:22

+0

@tunedin你可以使用for循環,但它會是$ photos [$ i] ['filename']。 – C9HDN 2013-03-22 02:47:14

+0

@Calum你能舉個例子嗎? – tunedin 2013-03-22 02:49:04