动态地替换所有< img>的“src”属性标签(redux) [英] Dynamically replace the “src” attributes of all <img> tags (redux)

查看:133
本文介绍了动态地替换所有< img>的“src”属性标签(redux)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

动态替换src所有< img>的属性标签

有趣的故事:我发布了这个问题很早以前,而不是得到一些可以的东西,你知道,使用,我得到了很多关于使用正则表达式来解析HTML的恶魔的教条。所以这里再一次。

Funny story: I posted this very question a short time ago, but instead of getting something I could, you know, use, all I got was a lot of dogma about the evils of using regex to parse HTML. So here goes again.

我有一些HTML,想要替换所有img标签的src属性,以便它们指向相同图像的副本(尽管在另一个主机上使用不同的文件名。

I have some HTML and want to replace the "src" attributes of all the img tags so that they point to copies of the identical images (although with different file names) on another host.

例如,给定这三个标签

<IMG SRC="../graphics/pumpkin.gif" ALT="pumpkin">
<IMG BORDER="5" SRC="redball.gif" ALT="*"> 
<img alt="cool image" src="http://www.crunch.com/pic.jpg"/>

我希望他们替换为

<IMG SRC="http://myhost.com/cache/img001.gif" ALT="pumpkin">
<IMG BORDER="5" SRC="http://myhost.com/cache/img002.gif" ALT="*"> 
<img alt="cool image" src="http://myhost.com/cache/img003.jpg"/>

我试图使用 PHP简单的HTML DOM解析器,但我没有得到它。

I am trying to use PHP Simple HTML DOM Parser, but I'm not getting it.

include 'simple_html_dom.php';
$html = str_get_html('<html><body>
<IMG SRC="../graphics/pumpkin.gif" ALT="pumpkin">
<IMG BORDER="5" SRC="redball.gif" ALT="*"> 
<img alt="cool image" src="http://www.crunch.com/pic.jpg"/>
</body></html>');

下一步该怎么办?

推荐答案

如果你关心DOMDocument()的方式:

If you care to go the way of DOMDocument():

$dom=new DOMDocument();
$dom->loadHTML($your_html);
$imgs = $dom->getElementsByTagName("img");
foreach($imgs as $img){
    $alt = $img->getAttribute('alt');
    if ($alt == 'pumpkin'){
        $src = 'http://myhost.com/cache/img001.gif';    
    } else if ($alt== '*'){
        $src = 'http://myhost.com/cache/img002.gif';
    } else if ($alt== 'cool image'){
        $src = 'http://myhost.com/cache/img003.jpg';
    }
    $img->setAttribute( 'src' , $src );
}

这篇关于动态地替换所有&lt; img&gt;的“src”属性标签(redux)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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