Facebook Meta Tag PHP condition


Facebook Meta Tag PHP condition

我在尝试获取此代码片段以为数组中的每个图像输出单独的 og:image 元标记时遇到问题。

 <?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];

}

?>

"/>

我仍然想不通。 有什么想法吗?

试试这个函数。它将返回一个图像源数组。然后,您始终可以使用数组中的第一个图像作为默认图像。

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">';
}