Aref Anafgeh
Aref Anafgeh

Reputation: 512

Find image src with regex in PHP

How can I extract image src from an text that only contains img tag? And by the way src is double quote sometimes and in single quote sometimes.

Upvotes: 1

Views: 3949

Answers (2)

Eaten by a Grue
Eaten by a Grue

Reputation: 22931

I would not recommend using regex to parse html. Instead you can use php's DOMDocument() class, which should still work even if the rest of the string isn't really html:

$html = 'Lorem ipsum<img src="test.png">dolor sit amet&[H*()';

libxml_use_internal_errors(true);
$dom = new DOMDocument();
$dom->loadHTML($html);
$imgs = $dom->getElementsByTagName('img');
foreach($imgs as $img) {
    $src = $img->getAttribute('src'); 
    echo $src;
}

Depending on your php version you may also want to use:

$dom->loadHTML($a, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

Upvotes: 6

Hassaan
Hassaan

Reputation: 7662

Try

$image = '<img class="foo bar test" title="test image" src=\'http://example.com/img/image.jpg\' alt="test image" width="100" height="100" />';
$array = array();
preg_match( "/src='([^\"]*)'/i", $image, $array ) ;
print_r( $array[1] ) ;

Upvotes: 1

Related Questions