开发者

Dynamically replace the “src” attributes of all <img> tags (redux) [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Dynamically replace the “src” attributes of all <img> tags

开发者_开发技巧

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.

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.

For instance, given these three tags

<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"/>

I would like them replaced with

<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"/>

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

What do I do next?


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


The link you posted has the answer:

// 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>

Of course, you will need to modify the tag/attribute/value names to meet your specific needs.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜