2

i have no idea about php regex i wish to extract all image tags <img src="www.google.com/exampleimag.jpg"> form my html how can i do this using preg_match_all

thanks SO community for u'r precious time

well my scenario is like this there is not whole html dom but just a variable with img tag $text="this is a new text <img="sfdsfdimg/pfdg.fgh" > there is another iamh <img src="sfdsfdfsd.png"> hjkdhfsdfsfsdfsd kjdshfsd dummy text

spiderman
  • 1,397
  • 2
  • 10
  • 18

2 Answers2

4

Don't use regular expressions to parse HTML. Instead, use something like the DOMDocument that exists for this very reason:

$html = 'Sample text. Image: <img src="foo.jpg" />. <img src="bar.png" />';
$doc = new DOMDocument();
$doc->loadHTML( $html );

$images = $doc->getElementsByTagName("img");

for ( $i = 0; $i < $images->length; $i++ ) {
  // Outputs: foo.jpg bar.png
  echo $images->item( $i )->attributes->getNamedItem( 'src' )->nodeValue;
}

You could also get the image HTML itself if you like:

// <img src="foo.jpg" />
echo $doc->saveHTML ( $images->item(0) );
Sampson
  • 265,109
  • 74
  • 539
  • 565
1

You can't parse HTML with regex. You're much better off using the DOM classes. They make it trivially easy to extract the images from a valid HTML tree.

$doc = new DOMDocument ();
$doc -> loadHTML ($html);
$images = $doc -> getElementsByTagName ('img'); // This will generate a collection of DOMElement objects that contain the image tags
Community
  • 1
  • 1
GordonM
  • 31,179
  • 15
  • 87
  • 129