1

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.

Muhammad Hassaan
  • 7,296
  • 6
  • 30
  • 50
Aref Anafgeh
  • 512
  • 1
  • 6
  • 20

2 Answers2

6

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);
1

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] ) ;
Muhammad Hassaan
  • 7,296
  • 6
  • 30
  • 50