Dynamically replace the “src” attributes of all

2020-02-13 03:42发布

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?

标签: php parsing dom
2条回答
我命由我不由天
2楼-- · 2020-02-13 04:37

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 );
}
查看更多
狗以群分
3楼-- · 2020-02-13 04:42

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.

查看更多
登录 后发表回答