html-使用PHP获取img src
在此示例中,我想将SRC属性转换为变量:
因此,例如-我想获取一个变量$foo = "/images/image.jpg"。重要! src属性将是动态的,因此不能进行硬编码。有什么快速简便的方法可以做到这一点?
谢谢!
编辑:图像将是一个巨大的字符串的一部分,基本上是新闻故事的内容。 因此,图像只是其中的一部分。
EDIT2:该字符串中将包含更多图像,我只想获取第一个图像的src。 这可能吗?
7个解决方案
97 votes
使用类似DOMDocument的HTML解析器,然后使用DOMXpath评估您要查找的值:
$html = '
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"
或对于那些确实需要节省空间的人:
$xpath = new DOMXPath(@DOMDocument::loadHTML($html));
$src = $xpath->evaluate("string(//img/@src)");
对于那里的一线客:
$src = (string) reset(simplexml_import_dom(DOMDocument::loadHTML($html))->xpath("//img/@src"));
hakre answered 2020-02-16T15:13:00Z
21 votes
使用DOM解析器进行这种HTML解析会更好。 考虑以下代码:
$html = '
alt="Image" width="100" height="100" />';
$doc = new DOMDocument();
libxml_use_internal_errors(true);
$doc->loadHTML($html); // loads your html
$xpath = new DOMXPath($doc);
$nodelist = $xpath->query("//img"); // find your image
$node = $nodelist->item(0); // gets the 1st image
$value = $node->attributes->getNamedItem('src')->nodeValue;
echo "src=$value\n"; // prints src of image
输出:
src=/images/image.jpg
anubhava answered 2020-02-16T15:13:24Z
14 votes
我已经用更简单的方法做到了,虽然不尽如人意,但这是一个快速的技巧。
$htmlContent = file_get_contents('pageURL');
// read all image tags into an array
preg_match_all('/]+>/i',$htmlContent, $imgTags);
for ($i = 0; $i < count($imgTags[0]); $i++) {
// get the source string
preg_match('/src="([^"]+)/i',$imgTags[0][$i], $imgage);
// remove opening 'src=' tag, can`t get the regex right
$origImageSrc[] = str_ireplace( 'src="', '', $imgage[0]);
}
// will output all your img src's within the html string
print_r($origImageSrc);
Torsten answered 2020-02-16T15:13:44Z
10 votes
我知道有人说您不应该使用正则表达式来解析HTML,但是在这种情况下,我发现它非常好。
$string = '';
preg_match('/
$foo = array_pop($result);
kba answered 2020-02-16T15:14:04Z
5 votes
$imgTag = <<< LOB
LOB;
preg_match('%%i', $imgTag, $matches);
$imgSrc = $matches[1];
演示
注意:您应该使用HTML解析器,例如DOMDocument,而不是正则表达式。
Pedro Lobito answered 2020-02-16T15:14:29Z
3 votes
$str = '';
preg_match('/(src=["\'](.*?)["\'])/', $str, $match); //find src="X" or src='X'
$split = preg_split('/["\']/', $match[0]); // split by quotes
$src = $split[1]; // X between quotes
echo $src;
其他正则表达式可以用来确定所拉出的src标签是否是类似这样的图片:
if(preg_match('/([jpg]{3}$)|([gif]{3}$)|([jpeg]{3}$)|([bmp]{3}$)|([png]{3}$)/', $src) == 1) {
//its an image
}
squarephoenix answered 2020-02-16T15:14:49Z
-1 votes
可能有两个简单的解决方案:
HTML本身就是一个XML,所以如果您将标记加载为XML并动态地动态获取其属性(甚至是dom数据属性,例如data-time或其他任何内容),则可以使用任何XML解析方法。
对php使用任何html解析器喜欢[http://mbe.ro/2009/06/21/php-html-to-array-working-one/]要么PHP解析HTML数组谷歌这
Jitendra answered 2020-02-16T15:15:18Z