如何从HTML文档中获取IMG标签代码? [英] How to get IMG tag code from HTML document?

查看:177
本文介绍了如何从HTML文档中获取IMG标签代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从文本中获取img代码? 现在,如果标签如下所示,我将获得代码和URL:text text <img src = "image.gif" />,但是如果代码为<img src = "image.gif" target = _blank />,则将获得URL:"image.gif" target = _blank.

how I get the img code from a text? Now I get the code and URL if the tag looks like: text text <img src = "image.gif" />, but if the code is <img src = "image.gif" target = _blank />, then I get the URL: "image.gif" target = _blank.

那么,如何正确找到img的完整代码和URL?

So, how correctly find img full code and URL?

谢谢

preg_match_all('/\<img src = (.*?)\/>/', $input, $all_img);

推荐答案

不要尝试使用正则表达式解析HTML;使用HTML解析器,例如 PHP的DOM库

Don’t try to parse HTML with regular expressions; use an HTML parser like PHP’s DOM library or the PHP Simple HTML DOM Parser instead (see Gordon’s comment for further alternatives).

下面是一个使用PHP简单HTML DOM解析器的示例:

Here’s an example with the PHP Simple HTML DOM Parser:

$html = str_get_html('…');
foreach ($html->find('img[src]') as $img) {
    echo $img->getAttribute('src');
}

这篇关于如何从HTML文档中获取IMG标签代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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