user1992794
user1992794

Reputation: 7

Regex matching specific html tags

I'm doing form that let's user send me html code that contains image links. Like this:

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

Now I'm trying to use RegEx to select only a and img HTML tags where img can be <img />, <img> </img> or <img>. I don't already now is there width, height or something else set, but they should also came along with RegEx. If there is anyother HTML tag it should not come with RegEx.

So basicly if there is HTML code like this:

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

RegEx should return these:

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

I hope you understand what I am looking for.

Upvotes: 0

Views: 6192

Answers (1)

Sergey Khalitov
Sergey Khalitov

Reputation: 1027

Your RegExp solution is:

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

PHP example:

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

JavaScript example:

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

Upvotes: 1

Related Questions