Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get img src with PHP

I would like to get the SRC attribute into a variable in this example:

<img border="0" src="/images/image.jpg" alt="Image" width="100" height="100" /> 

So for example - I would like to get a variable $foo = "/images/image.jpg". Important! The src attribute will be dynamic, so it mustn't be hardcoded. Is there any quick and easy way to do this?

Thanks!

EDIT: The image will be a part of a huge string that is basically the content of a news story. So the image is just a part of that.

EDIT2: There will be more images in this string, and I would only want to get the src of the first one. Is this possible?

like image 718
pangi Avatar asked Apr 12 '12 19:04

pangi


People also ask

How to get image src in php?

To get the src of the image tag we are going to use the regular expression of @src="([^"]+)"@. $html = '<img border="0" src="/images/image. jpg" alt="Image" width="100" height="100" />'; preg_match( '@src="([^"]+)"@' , $html, $match ); $src = array_pop($match); // will return /images/image.

How to use image tag in php?

Just echo the HTML code ( in your case , the <img> tag ) in PHP , just like you did for <a> tag.


1 Answers

Use a HTML parser like DOMDocument and then evaluate the value you're looking for with DOMXpath:

$html = '<img id="12" border="0" src="/images/image.jpg"          alt="Image" width="100" height="100" />';  $doc = new DOMDocument(); $doc->loadHTML($html); $xpath = new DOMXPath($doc); $src = $xpath->evaluate("string(//img/@src)"); # "/images/image.jpg" 

Or for those who really need to save space:

$xpath = new DOMXPath(@DOMDocument::loadHTML($html)); $src = $xpath->evaluate("string(//img/@src)"); 

And for the one-liners out there:

$src = (string) reset(simplexml_import_dom(DOMDocument::loadHTML($html))->xpath("//img/@src")); 
like image 152
hakre Avatar answered Sep 19 '22 08:09

hakre