【问题标题】:How to get class and src from html image tag如何从 html 图像标签中获取类和 src
【发布时间】:2018-03-03 06:22:34
【问题描述】:

我想使用正则表达式检索图像标签的类和srcclasssrc 的位置可以在任何位置。

我可以从/<img[^>]* src="([^\"]+)"[^>]*>/i得到src

<img width="100" height="100" src="/woocom.png" class="hello hel" alt="woo">

<img width="100" height="100" class="hello hel" src="/woocom.png"  alt="woo">`

Tried Online Regex here

【问题讨论】:

标签: php regex


【解决方案1】:

因为有一个 PHP 标签。我不建议在这种情况下使用正则表达式。正则表达式是一把锤子,当你理解它时,你周围的一切看起来都像钉子。在 PHP 中,我们有用于此任务的 DOMDocument 类。例如下面:

$d = new DOMDocument();
$d->loadHTML('<img width="100" height="100" src="/woocom.png" class="hello hel" alt="woo">');
$images = $d->getElementsByTagName('img');
foreach ($images as $image) {
  echo $image->getAttribute('src');
  echo $image->getAttribute('class');
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-19
    相关资源
    最近更新 更多