【问题标题】:Dynamically replace the “src” attributes of all <img> tags (redux) [duplicate]动态替换所有 <img> 标签的“src”属性(redux)[重复]
【发布时间】:2010-09-27 23:55:43
【问题描述】:

可能重复:
Dynamically replace the “src” attributes of all <img> tags

有趣的故事:我不久前发布了this very question,但我没有得到我可以使用的东西,你知道,我得到的只是很多关于使用正则表达式解析 HTML 的弊端的教条。所以又来了。

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

例如,给定这三个标签

<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 Simple HTML DOM Parser,但我不明白。

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>');

接下来我该怎么做?

【问题讨论】:

标签: php parsing dom


【解决方案1】:

如果你想走 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 );
}

【讨论】:

    【解决方案2】:

    您发布的链接有答案:

    // Create DOM from string
    $html = str_get_html('<div id="hello">Hello</div><div id="world">World</div>');
    
    $html->find('div', 1)->class = 'bar';
    
    $html->find('div[id=hello]', 0)->innertext = 'foo';
    
    echo $html; // Output: <div id="hello">foo</div><div id="world" class="bar">World</div>
    

    当然,您需要修改标签/属性/值名称以满足您的特定需求。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-19
      • 2023-03-09
      • 2013-12-06
      • 2012-01-12
      • 1970-01-01
      • 2013-05-26
      • 1970-01-01
      • 2014-03-12
      相关资源
      最近更新 更多