1

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.

1
  • 1
    You shouldn't use regex to parse html as explained here If you still want to do this, add what is your flavor (what language are you in) Commented Jun 7, 2016 at 16:42

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.