如果preg_match_all()为null,如何返回图像

时间:2014-01-04 06:27:15

标签: php wordpress

我有这个功能:

function mom_get_first_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)) {

        return "images/logo.png";
    } else {
        return $first_img;
    }
}

这个功能是显示帖子,如果我的网站首页上有图片显示我,但如果没有图片,我需要显示我网站的标识。

如果没有图片,我会尝试获取徽标,但它会告诉我:

<img title="title" alt="title" src="" style="opacity: 1;">

如果有图像,请告诉我:

<img title="title" alt="title" src="images/111.jpg" style="opacity: 1;">

我的问题在哪里?

2 个答案:

答案 0 :(得分:0)

我认为问题在于你的正则表达式。如果属性为空,则不会捕获该属性,因为它至少需要一个非引号的字符。你必须改变它,以便它需要0或更多。如果你把它改成它就会捕获它。

'/<img.+src=[\'"]([^\'"]*)[\'"].*>/i'

答案 1 :(得分:0)

function mom_get_first_image()
{
    global $post;
    if(preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches))
        $first_img = $matches[1][0];
    else
        $first_img = "images/logo.png";
    return $first_img;
}