tags:

views:

49

answers:

3
$variable = '<img src="http://www.gravatar.com/avatar/66ce1f26a725b2e063d128457c20eda1?s=32&amp;d=identicon&amp;r=PG" height="32" width="32" alt=""/>';

How to get src of this image?

Like:

$src = 'http://www.gravatar.com/avatar/66ce1f26a725b2e063d128457c20eda1?s=32&amp;d=identicon&amp;r=PG';

Thanks.

+4  A: 

You can use an html parser for this. See this one: http://simplehtmldom.sourceforge.net/ (I hope this works for nodes, not just for entire pages).

greg0ire
Suggested third party alternatives that actually use DOM instead of String Parsing: [phpQuery](http://code.google.com/p/phpquery/), [Zend_Dom](http://framework.zend.com/manual/en/zend.dom.html), [QueryPath](http://querypath.org/) and [FluentDom](http://www.fluentdom.org). However, for the OP's UseCase, a HTML/DOM Parser might be overkill.
Gordon
+3  A: 

use regex

preg_match( '@src="([^"]+)"@' , $variable , $match );

And src will be in $match, see print_r( $match ). But this is only for this situation, if you want universal solution (like ' against " etc.) use html/DOM parser.

killer_PL
Actually one of the rare cases where I think a Regex is justified and better suited than a full blown HTML parser for getting to the desired outcome.
Gordon
this regex doesn't work, gives empty array
Happy
@WorkingHard works fine for me
Gordon
+1  A: 

Use HTML DOM. Download and include simple_html_dom.php file in your script.

Then get image URLs like this:

$html = str_get_html('<img src="http://www.gravatar.com/avatar/66ce1f26a725b2e063d128457c20eda1?s=32&amp;d=identicon&amp;r=PG" height="32" width="32" alt=""/>');

// Find all images
foreach($html->find('img') as $element)
       echo $element->src . '<br>';
NAVEED