2016-06-07 131 views
0

我正在做的形式,讓我們的用戶發送給我的HTML代碼,其中包含圖像鏈接。就像這樣:正則表達式匹配特定的html標籤

<a href="http://linklocation.com" target="_blank"><img src="http://imagelocation.com" border="0"></a> 
<a href="http://linklocation.com" target="_blank"><img src="http://imagelocation.com" border="0"></a> 
<a href="http://linklocation.com" target="_blank"><img src="http://imagelocation.com" border="0"></a> 
<a href="http://linklocation.com" target="_blank"><img src="http://imagelocation.com" border="0"></a> 
<a href="http://linklocation.com" target="_blank"><img src="http://imagelocation.com" border="0" width="100px" height="100px"></a> <br> 

現在我試圖用正則表達式只選擇aimg HTML標籤,其中IMG可以<img /><img></img><img>。我現在還沒有設置寬度,高度或其他設置,但它們也應該與RegEx一起出現。如果有任何其他HTML標籤,則不應使用RegEx。

所以basicly如果有HTML代碼:

<a href="http://linklocation.com" target="_blank"><img src="http://imagelocation.com" border="0"></a> 
<a href="http://linklocation.com" target="_blank"><p>Hello world!</p></a> <script>Something</script> 
<a href="http://linklocation2.com" target="_blank"><img src="http://imagelocation2.com" border="0" width="200px" height="20px"></a> 

正則表達式應該返回這些:

<a href="http://linklocation.com" target="_blank"><img src="http://imagelocation.com" border="0"></a> 
<a href="http://linklocation2.com" target="_blank"><img src="http://imagelocation2.com" border="0" width="200px" height="20px"></a> 

我希望你明白我所期待的。

+1

你不應該使用正則表達式來解析HTML作爲解釋[這裏]( http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags)如果你仍然想這樣做,添加什麼是你的味道(你在用什麼語言) –

回答

0

你的正則表達式的解決方案是:

/<a\s*.*?><img\s*.*?<\/a>/ 

PHP例子:

$string = '<YOUR TEXT HERE>'; 
preg_match_all('#<a\s*.*?><img\s*.*?</a>#', $string, $matches); 
print_r($matches[0]); 

JavaScript示例:

var string = '<YOUR TEXT HERE>'; 
var matches = string.match(/<a\s*.*?><img\s*.*?<\/a>/g); 
console.log(matches)