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

7
  • You just want all images, regardless what their src value is? Commented May 1, 2012 at 6:12
  • 1
    Don't use regex to parse HTML; read up on DomDocument - php.net/domdocument Commented May 1, 2012 at 6:12
  • Use a PHP HTML parser instead of a regex. HTML and regular expressions don't mix well. Commented May 1, 2012 at 6:12
  • @JonathanSampson do i need domdocument too when my scenario is as above Commented May 1, 2012 at 6:20
  • @spiderman I just tested your text, and it found the image just fine. Commented May 1, 2012 at 6:21

2 Answers 2

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) );
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.