Extract the src attribute from an img tag

Hi,

I’ve tried several patterns to get the src attribute from an img tag, but I can’t find the answer.

This is what I’m currently trying:

preg_match('/src="(.*)|[^"]"/iS', $img, $src)
preg_match('/src="(.*)/iS', $img, $src)

The first one doesn’t work at all, and the second one gets everything to the right of src="

Wanna help a regexp newbie? Thanks in advance!

try this


$string = '<img src="/test">';
if(preg_match('/<img(.*)src=(\\'|")(.*)(\\'|")/i',$string,$match))
	print_r($match);

Thanks mate, but that doesn’t quite work:

This is the string: height=“85” alt=“” src=“syspax/ui/logo-ch.gif” width=“183” border=“0”

The code:

preg_match(‘/(.)src=(\'|")(.)(\’|")/i’, $img, $src); // removed the img tag, see above

This is what I get ($src):

Array
(
[0] => height=“85” alt=“” src=“syspax/ui/logo-ch.gif” width=“183” border=“0”
[1] => height=“85” alt=“”
[2] => "
[3] => syspax/ui/logo-ch.gif" width=“183” border="0
[4] => "
)

Any other ideas?

This solves it, but I wish I could do it inside the preg_match:

$src = substr($src[1], 0, strpos($src[1], '"'))

again try the following


$string = 'height="85" alt="" src="syspax/ui/logo-ch.gif" width="183" border="0"';
if(preg_match('/src=(\\'|")(.*?)(\\'|")/',$string,$match))
	print_r($match);


thanks :slight_smile: