如何从html图像标签中获取class和src [英] How to get class and src from html image tag

查看:76
本文介绍了如何从html图像标签中获取class和src的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用正则表达式检索图像标签的类和 src.classsrc 的位置可以任意.

I want to retrieve the class and src of image tag using regex. The position of class and src can be anywhere.

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

I am able to get src from /<img[^>]* src="([^\"]+)"[^>]*>/i

<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">`

在此处尝试在线正则表达式

推荐答案

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

Since there is a PHP tag. I won't recommend using Regular Expressions for this situation. Regular Expression is a hammer and when you understand it, everything around you looks like nail. In PHP we have DOMDocument class for this task. Eg below:

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

这篇关于如何从html图像标签中获取class和src的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆