2012-04-17 49 views
0

我有一個問題,試圖讓這個代碼片段爲數組中的每個圖像輸出一個單獨的og:image meta標籤。Facebook元標籤PHP條件

<?php function catch_that_image() { 
global $post, $posts; 
$first_img = ''; 
ob_start(); 
ob_end_clean(); 
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches); 
$first_img = $matches [1] [0]; 
if(empty($first_img)){ 
     //Defines a default image 
     $first_img = "http://example.com/images/fbthumb.jpg"; 
    } 
return $first_img; 
} 
?> 

目前的代碼返回第一個匹配的IMG SRC標記,但我想這是他們都返回作爲單獨的標籤,所以我可以選擇要使用的共享圖像。

我知道這行:

$first_img = $matches [1] [0]; 

需要改變成每個條件某種類型的,但林不知道怎麼樣。任何幫助將不勝感激。謝謝!

編輯:

這裏是最後的建議後,我的代碼:

<?php function catch_that_image() { 
global $post, $posts; 
$result = preg_match_all('#<img.+src=[\'"]([^\'"]+)[^>]*>#i', $post->post_content, $matches); 

return $matches[1]; 

}

>

「/>

我仍然無法數字出來? 。任何想法?

+0

'] *>#i',$ post-> post_content,$ matches); foreach($ matches [1] as $ match){ $ imgSources [] = $ match; } return $ imgSources; } > <元屬性= 「OG:圖像」 CONTENT = 「?」?/>' – brianr1 2012-04-17 17:43:04

回答

0

試試這個功能。它將返回一組圖像源。然後,您可以始終將陣列中的第一個圖像用作默認圖像。

function catch_that_image() { 
    global $post, $posts; 
    $imgSources = array(); 
    $result = preg_match_all('#<img.+src=[\'"]([^\'"]+)[^>]*>#i', $post->post_content, $matches); 

    foreach($matches[1] as $match) { 
     $imgSources[] = $match; 
    } 

    return $imgSources; 
} 

或簡單

function catch_that_image() { 
    global $post, $posts; 
    $result = preg_match_all('#<img.+src=[\'"]([^\'"]+)[^>]*>#i', $post->post_content, $matches); 

    return $matches[1]; 
} 

使用功能:

$imageArray = catch_that_image(); 
foreach($imageArray as $image) { 
    echo '<meta property=​"og:​image" content=​"$image">'; 
} 
+0

沒關係,所以我使用最後一個你給我在這裏,它仍然沒有返回值。我無法弄清楚如何將代碼添加到這個,所以我添加一個編輯到我原來​​的帖子。 – brianr1 2012-04-17 09:40:02

+0

在firebug中返回它: brianr1 2012-04-17 09:46:32