如何使用PHP帮助在div中找到图像?

时间:2017-12-29 08:06:46

标签: php jquery css

有div和div图像:

<div class="post entry-content ">

<img class="bbc_img" alt="Posted Image" src="http://example.com/image.jpg">

</div>

我需要帮助php中的div中的fing图像,它与此代码相同:

preg_match('IMAGE.JPG', $DIV_CLASS, $matches); 
if ($matches[1])
{
    echo $matches[1];
}

或者找到class =&#34; bbc_img&#34;在HTML中

3 个答案:

答案 0 :(得分:2)

使用DOMDocumentXPath执行此操作要比使用正则表达式简单得多

$strhtml='
    <div class="post entry-content">
        <img class="bbc_img" alt="Posted Image" src="http://example.com/image.jpg">
    </div>';

    $dom=new DOMDocument;
    $dom->loadHTML( $strhtml );
    $xp=new DOMXPath( $dom );
    $col=$xp->query('//div[ contains(@class,"entry-content" ) ]/img[@class="bbc_img"]');

    if( $col->length > 0 ){
        foreach( $col as $node )echo $node->getAttribute('src');
    }

答案 1 :(得分:0)

使用JQuery,您可以在DOM解析的帮助下轻松完成此任务。

HTML

<div class="post-entry-content">
  <img class="bbc_img" alt="Posted Image" src="http://example.com/image.jpg">
</div>

JS

$(document).ready(function() {
  if ($(".post-entry-content .bbc_img").length > 0) {
    alert("div contains image with class bbc_img");
  }
});

请参阅此小提琴https://jsfiddle.net/Lwv7q09c/

答案 2 :(得分:0)

尝试这种方式:

$div= '<div class="post entry-content ">
<img class="bbc_img" alt="Posted Image" src="http://example.com/image.jpg">
</div>';

preg_match('/src="(.*)"/i', $div, $matches, PREG_OFFSET_CAPTURE);
$img = $matches[0][0];