2013-07-24 38 views
1

我在閱讀html內容。有圖像標記,如正則表達式提取圖像鏈接

<img onclick="document.location='http://abc.com'" src="http://a.com/e.jpg" onload="javascript:if(this.width>250) this.width=250"> 

<img src="http://a.com/e.jpg" onclick="document.location='http://abc.com'" onload="javascript:if(this.width>250) this.width=250" /> 

我試圖重新格式化該標籤成爲

<img src="http://a.com/e.jpg" /> 

但是我不是成功的。我試圖建立迄今爲止的代碼就像

$image=preg_replace('/<img(.*?)(\/)?>/','',$image); 

任何人都可以幫忙嗎?

+0

這不是正則表達式的任務。改爲使用HTML解析器。 –

回答

1

下面是使用DOM文檔的一個版本,可以消除<img>標籤的所有屬性除了src屬性。請注意,使用DOMDocument執行loadHTMLsaveHTML也可以更改其他html,特別是如果該html格式錯誤。所以要小心 - 測試結果是否可以接受。

<?php 

$html = <<<ENDHTML 
<!doctype html> 
<html><body> 
<a href="#"><img onclick="..." src="http://a.com/e.jpg" onload="..."></a> 

<div><p> 
<img src="http://a.com/e.jpg" onclick="..." onload="..." /> 
</p></div> 
</body></html> 
ENDHTML; 

$dom = new DOMDocument; 
if (!$dom->loadHTML($html)) { 
    throw new Exception('could not load html'); 
} 

$xpath = new DOMXPath($dom); 

foreach ($xpath->query('//img') as $img) { 
    // unfortunately, cannot removeAttribute() directly inside 
    // the loop, as this breaks the attributes iterator. 
    $remove = array(); 
    foreach ($img->attributes as $attr) { 
     if (strcasecmp($attr->name, 'src') != 0) { 
      $remove[] = $attr->name; 
     } 
    } 

    foreach ($remove as $attr) { 
     $img->removeAttribute($attr); 
    } 
} 

echo $dom->saveHTML(); 
0

匹配一次一個然後Concat的字符串,我不能確定你使用的是如此虐待僞解釋的語言:

1.Find <img with regex place match in a string variable 
2.Find src="..." with src=".*?" place match in a string variable 
3.Find the end /> with \/> place match in a string variable 
4.Concat the variables together