php:在特定的div中找到一个url图像

时间:2014-07-03 13:52:56

标签: php html regex image

我有这段代码:

if (!$thumbdone) {
    if (intval($fb_image_use_content)==1) {
        $imgreg = '/<img .*src=["\']([^ ^"^\']*)["\']/';
        preg_match_all($imgreg, trim($post->post_content), $matches);
        if (isset($matches[1][0])) {
            //There's an image on the content
            $image=$matches[1][0];
            $pos = strpos($image, site_url());
            if ($pos === false) {
                if (stristr($image, 'http://') || stristr($image, 'https://')) {
                    //Complete URL - offsite
                    $fb_image=$image;
                } else {
                    $fb_image=site_url().$image;
                }
            } else {
                //Complete URL - onsite
                $fb_image=$image;
            }
            $thumbdone=true;
        }
    }
}

在代码中查找第一个图像。 问题是我想找到以这种方式构造的div中的第一个图像:

<div style="display:block" class="ogimage">
<img class="aligncenter wp-image-1030 size-full" src="http:/site.com/image.jpg" alt="image" width="600" height="315">
</div>

我用Google搜索了这个: https://www.google.it/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=php%20get%20image%20from%20div

我也试过了http://www.phpliveregex.com/

但没有。帮助

2 个答案:

答案 0 :(得分:2)

使用正确的tool作为作业,而不是尝试使用正则表达式解析HTML。

$doc = new DOMDocument();
$doc->loadHTML($html);

$xpath = new DOMXPath($doc);
$img   = $xpath->query('//div[@class="ogimage"]/img');

echo $img->item(0)->getAttribute('src');

Working Demo

答案 1 :(得分:0)

您可以像这样使用explode

$html = '<div style="display:block" class="ogimage"><img class="aligncenter wp-image-1030 size-full" src="http:/site.com/image.jpg" alt="image" width="600" height="315"></div>';
$result = explode($html)[7];