2010-09-27 65 views
1

可能重複:
Dynamically replace the 「src」 attributes of all <img> tags動態替換所有<img>標籤的「SRC」屬性(終極版)

滑稽的故事:我張貼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>'); 

接下來我該做什麼?

+0

你有()嘗試使用DOM文檔? – KeatsKelleher 2010-09-28 00:00:49

+1

投票以重複關閉[動態替換所有標記的「src」屬性](http://stackoverflow.com/questions/3808285/dynamically-replace-the-src-attributes-of-all-img-tags ),因爲這不是做這件事的方法,但你說得對,答案可能更重要(儘管檢查DOM文檔並不困難,而且我覺得它更容易(主觀),並且(目標),然後'簡單的HTML DOM解析器') – Wrikken 2010-09-28 00:11:50

回答

1

您發佈的鏈接都有了答案:

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

當然,你將需要修改標籤/屬性/值名稱,以滿足您的特定需求。

6

如果你願意去DOM文檔()的方法:

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