【问题标题】:How to find image in div with help PHP?如何在帮助 PHP 的情况下在 div 中查找图像?
【发布时间】:2017-12-29 08:06:45
【问题描述】:

有 div 和在 div 图片中:

<div class="post entry-content ">

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

</div>

我需要在 div 中使用帮助 php 查找图像,与此代码相同:

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

或者在html中查找带有class="bbc_img"的图片

【问题讨论】:

  • 要使用jQuery...?
  • regex 对于这类任务来说是出了名的棘手和不可靠 - imo,使用 DOMDocumentDOMXPath 甚至是等效的 javascript 方法会更好
  • 但是为什么呢?你想做什么? PHP/Jquery/CSS 标签?哪一个?

标签: php jquery css


【解决方案1】:

使用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');
    }

【讨论】:

  • 这对我有用。谢谢你。但是example.com/image.jpg这个图片可以是随机的url。
  • 可以使用相同的代码,但您需要编辑 XPath 查询以适应 html 内容 - 或者只是制作一个非常贪婪的模式,例如 $xp-&gt;query('//img'); ~ 如果您发布了实际使用 -案例代码将有助于进一步澄清
  • m sorry. Im 不是 php 的编码员。请写完整代码。
【解决方案2】:

使用 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/

【讨论】:

  • 问题确实明确表示with help PHP
【解决方案3】:

试试这个方法:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-23
    • 2015-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-04
    • 1970-01-01
    相关资源
    最近更新 更多