12

I need to extract the src element from all image tags in an HTML document.

So, the input is an HTML page and the output would be a list of URL's pointing to images: ex... http://www.google.com/intl/en_ALL/images/logo.gif

The following is what I came up with so far:

<img\s+src=""(http://.*?)

This does not work for tags where the src isn't directly after the img tag, for example:

<img height="1px" src="spacer.gif">

Can someone help complete this regular expression? It's pretty easy, but I thought this may be a faster way to get an answer.

4 Answers 4

31

The following regexp snippet should work.

<img[^>]+src="([^">]+)"

It looks for text that starts with <img, followed by one or more characters that are not >, then src=". It then grabs everything between that point and the next " or >.

But if at all possible, use a real HTML parser. It's more solid, and will handle edge cases much better.

5
  • 4
    It won't work for single quoted tags, and remember that HTML actually doesn't require quotes on attributes unless they contain whitespace.
    – Lucero
    Jun 22, 2009 at 17:12
  • also wont work if there is a tag ending with the letters src, for example if the image has a data-src tag this wont work. Dec 28, 2016 at 9:15
  • 9
    <img\s.*?src=(?:'|")([^'">]+)(?:'|") This looks for a string starting with <img; then one space; then 0 or more of anything; then src= single/double quotes (without capture); then capture one or more of anything that isn't a single/double quote or >; then a single/double quote (without capture). This one works for single/double quotes and won't pickup other attributes with "src" like data-src. phpliveregex.com/p/kDH
    – cfx
    Jul 5, 2017 at 8:11
  • <img\s.*?src=(?:'|\")([^'\">]+)(?:'|\").*?\/?> to capture the entire tag, incase you need to replace it.
    – zanderwar
    Apr 4, 2022 at 2:59
  • It works in escaped string as well having \n, \r, etc. May 26, 2022 at 12:34
11

You don't want to do that. Correctly parsing HTML is a very complex problem, and regular expressions are not a good tool for that.

See e.g. Can you provide some examples of why it is hard to parse XML and HTML with a regex?

And here for a good solution:

How do I programatically inspect a HTML document

5

You could do this pretty easily with Javascript. An example would be like below:

var images = document.getElementsByTagName("img");

for (i=0; i < images.length; i++)
{
   // get image src
   var currImage = images[i].src;

   // do link creation here
} 
2

This works great for me

$regexp = '<img[^>]+src=(?:\"|\')\K(.[^">]+?)(?=\"|\')';

if(preg_match_all("/$regexp/", $content, $matches, PREG_SET_ORDER)) {

    if( !empty($matches) ) {

        for ($i=0; $i <= count($matches); $i++)

        {
            $img_src = $matches[$i][0];

            echo $img_src;

        }

    }

}

Your Answer

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