Regular Expression to extract src attribute from img tag

This one only grabs the src only if it's inside of an tag and not when it is written anywhere else as plain text. It also checks if you've added other attributes before or after the src attribute.

Also, it determines whether you're using single (') or double (") quotes.

\<img.+src\=(?:\"|\')(.+?)(?:\"|\')(?:.+?)\>

So for PHP you would do:

preg_match("/\<img.+src\=(?:\"|\')(.+?)(?:\"|\')(?:.+?)\>/", $string, $matches);
echo "$matches[1]";

for JavaScript you would do:

var match = text.match(/\<img.+src\=(?:\"|\')(.+?)(?:\"|\')(?:.+?)\>/)
alert(match[1]);

Hopefully that helps.


Your pattern should be (unescaped):

src\s*=\s*"(.+?)"

The important part is the added question mark that matches the group as few times as possible

Tags:

Regex