2012-04-17 102 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