spiderman
spiderman

Reputation: 1417

php regex for finding image in a Text

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

Upvotes: 2

Views: 1805

Answers (2)

Sampson
Sampson

Reputation: 268512

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

Upvotes: 4

GordonM
GordonM

Reputation: 31790

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

Upvotes: 1

Related Questions