Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PHP: get image src attribute (regular expression)
<?php
// Source: http://goo.gl/qyLFbg
$html = '<img border="0" src="/images/image.jpg" alt="Image" width="100" height="100" />';
preg_match( '@src="([^"]+)"@' , $html, $match );
$src = array_pop($match);
// will return /images/image.jpg
echo $src;
@zikezhang

This comment has been minimized.

Copy link

zikezhang commented Mar 8, 2017

preg_match_all('/<img[^>]+>/i',$text, $result);

@kamleshpal1311

This comment has been minimized.

Copy link

kamleshpal1311 commented May 1, 2017

Hi,
If my html is like this $html = "<img border="0" src="/images/image1.jpg" alt="Image" width="100" height="100" /><img border="0" src="/images/image2.jpg" alt="Image" width="100" height="100" /><img border="0" src="/images/image3.jpg" alt="Image" width="100" height="100" />";

Then how can i get the all image tag src
Thanks
KamleshPal

@vyspiansky

This comment has been minimized.

Copy link
Owner Author

vyspiansky commented May 12, 2017

You can use the preg_match_all function. For instance:

$html = '
    <img border="0" src="/images/image1.jpg" alt="Image" width="100" height="100" />
    <img border="0" src="/images/image2.jpg" alt="Image" width="100" height="100" />
    <img border="0" src="/images/image3.jpg" alt="Image" width="100" height="100" />
    ';
preg_match_all( '@src="([^"]+)"@' , $html, $match );

$src = array_pop($match);
print_r($src);

Output:

Array (
    [0] => /images/image1.jpg
    [1] => /images/image2.jpg
    [2] => /images/image3.jpg
)
@hassanazimi

This comment has been minimized.

Copy link

hassanazimi commented Jun 9, 2018

preg_match('/<img.+src=[\'"](?P<src>.+?)[\'"].*>/i', $body, $result);
@hassanazimi

This comment has been minimized.

Copy link

hassanazimi commented Jun 9, 2018

preg_match('~<img.*?src=["\']+(.*?)["\']+~', $body, $result);
@cbahir

This comment has been minimized.

Copy link

cbahir commented Aug 16, 2018

Hy, in my case i have a html file which has store the view source of url and then i want to Get all 'img' tages with 'alt' from html file ,so what i do for this....

thanks in advance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.