正则表达式匹配特定的html标签

问题描述:

我正在做的形式,让我们的用户发送给我的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://*.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags)如果你仍然想这样做,添加什么是你的味道(你在用什么语言) –

你的正则表达式的解决方案是:

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