从字符串获取所有图像网址 [英] Get all images url from string

查看:141
本文介绍了从字符串获取所有图像网址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能存在重复:

如何从html中使用php提取img src,title和alt?



我找到了解决方案来从字符串中获取第一张图片:


Hi,
I have found solution to get first image from string:

preg_match('~<img[^>]*src\s?=\s?[\'"]([^\'"]*)~i',$string, $matches);

但我无法设法从字符串中获取所有图片。
还有一件事...如果图像包含替代文本( alt 属性),如何获取并保存到另一个变量?

在此先感谢,

Ilija

But I can't manage to get all images from string.
One more thing... If image contains alternative text (alt attribute) how to get it too and save to another variable?
Thanks in advance,
Ilija

推荐答案

这是我尝试过的,但无法获得src的打印值

This is what I tried but can't get it print value of src

 $dom = new domDocument;

    /*** load the html into the object ***/
    $dom->loadHTML($html);

    /*** discard white space ***/
    $dom->preserveWhiteSpace = false;

    /*** the table by its tag name ***/
    $images = $dom->getElementsByTagName('img');

    /*** loop over the table rows ***/
    foreach ($images as $img)
    {
        /*** get each column by tag name ***/
        $url = $img->getElementsByTagName('src');
        /*** echo the values ***/
        echo $url->nodeValue;
        echo '<hr />';
    }

编辑:我解决了这个问题

$dom = new domDocument;

/*** load the html into the object ***/
$dom->loadHTML($string);

/*** discard white space ***/
$dom->preserveWhiteSpace = false;

$images = $dom->getElementsByTagName('img');

foreach($images as $img)
    {
        $url = $img->getAttribute('src');   
        $alt = $img->getAttribute('alt');   
        echo "Title: $alt<br>$url<br>";
    }

这篇关于从字符串获取所有图像网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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