开发者

Just get the image URL from string in PHP [duplicate]

This question already has answers here: How to extract a node attribute from XML using PHP's DOM Parser (3 answers) 开发者_如何学运维 How do you parse and process HTML/XML in PHP? (31 answers) Closed 3 years ago.

From a string such as this <img src="/images/mylondon.jpg" /> I'm trying to retrieve JUST the url for use elsewhere in PHP

I know Regular expressions are the way to go, but I can't get my head around them right now.

Could anyone be of assistance?


preg_match_all('~<img.*?src=["\']+(.*?)["\']+~', $html, $urls);
$urls = $urls[1]


I think it would be better if used DOMDocument object:

$text = '<html><body><p>ala bala</p><img src="/images/mylondon.jpg" /></body></html>';
$htmlDom = new DOMDocument;
$htmlDom->loadHTML($text);

$imageTags = $htmlDom->getElementsByTagName('img');

$extractedImages = array();
foreach($imageTags as $imageTag){
   $extractedImages[] = $imageTag->getAttribute('src');
}

echo '<pre>'; var_dump($extractedImages); exit;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜