使用 PHP 获取 img src [英] Get img src with PHP

查看:49
本文介绍了使用 PHP 获取 img src的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在这个例子中将 SRC 属性放入一个变量中:

I would like to get the SRC attribute into a variable in this example:

<img border="0" src="/images/image.jpg" alt="Image" width="100" height="100" />

例如 - 我想获得一个变量 $foo = "/images/image.jpg".重要的!src 属性将是动态,所以它不能被硬编码.有什么快速简便的方法吗?

So for example - I would like to get a variable $foo = "/images/image.jpg". Important! The src attribute will be dynamic, so it mustn't be hardcoded. Is there any quick and easy way to do this?

谢谢!

图像将是一个大字符串的一部分,该字符串基本上是新闻故事的内容.所以图片只是其中的一部分.

The image will be a part of a huge string that is basically the content of a news story. So the image is just a part of that.

此字符串中会有更多图像,我只想获取第一个图像的 src.这可能吗?

There will be more images in this string, and I would only want to get the src of the first one. Is this possible?

推荐答案

使用像 DOMDocument 这样的 HTML 解析器,然后使用 DOMXpath 评估您要查找的值:

Use a HTML parser like DOMDocument and then evaluate the value you're looking for with DOMXpath:

$html = '<img id="12" border="0" src="/images/image.jpg"
         alt="Image" width="100" height="100" />';

$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$src = $xpath->evaluate("string(//img/@src)"); # "/images/image.jpg"

或者对于那些真正需要节省空间的人:

Or for those who really need to save space:

$xpath = new DOMXPath(@DOMDocument::loadHTML($html));
$src = $xpath->evaluate("string(//img/@src)");

对于单行者来说:

$src = (string) reset(simplexml_import_dom(DOMDocument::loadHTML($html))->xpath("//img/@src"));

这篇关于使用 PHP 获取 img src的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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