PHP get image src

2019-09-03 08:08发布

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

How to get src of this image?

Like:

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

Thanks.

标签: php src
3条回答
趁早两清
2楼-- · 2019-09-03 08:47

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.

查看更多
叛逆
3楼-- · 2019-09-03 08:58

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

查看更多
对你真心纯属浪费
4楼-- · 2019-09-03 09:05

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&d=identicon&r=PG" height="32" width="32" alt=""/>');

// Find all images
foreach($html->find('img') as $element)
       echo $element->src . '<br>';
查看更多
登录 后发表回答