Php 从由标记包装的字符串中查找图像链接
我需要提取只是图像链接作为一个div的背景图像使用Php 从由标记包装的字符串中查找图像链接,php,wordpress,Php,Wordpress,我需要提取只是图像链接作为一个div的背景图像使用 <a href="http://heartymagazine.com/wp-content/uploads/2014/07/watch-derek-jeter-jordan-brand-video.png"><img src="http://heartymagazine.com/wp-content/uploads/2014/07/watch-derek-jeter-jordan-brand-video.png" alt=""
<a href="http://heartymagazine.com/wp-content/uploads/2014/07/watch-derek-jeter-jordan-brand-video.png"><img src="http://heartymagazine.com/wp-content/uploads/2014/07/watch-derek-jeter-jordan-brand-video.png" alt="" title="watch-derek-jeter-jordan-brand-video" width="270" height="170" class="alignnone size-full wp-image-73989" /></a>
PHP。我无法处理正则表达式来提取图像url。请帮帮我
<a href="http://heartymagazine.com/wp-content/uploads/2014/07/watch-derek-jeter-jordan-brand-video.png"><img src="http://heartymagazine.com/wp-content/uploads/2014/07/watch-derek-jeter-jordan-brand-video.png" alt="" title="watch-derek-jeter-jordan-brand-video" width="270" height="170" class="alignnone size-full wp-image-73989" /></a>
试试这个:
$input $ = '<a href="http://heartymagazine.com/wp-content/uploads/2014/07/watch-derek-jeter-jordan-brand-video.png"><img src="http://heartymagazine.com/wp-content/uploads/2014/07/watch-derek-jeter-jordan-brand-video.png" alt="" title="watch-derek-jeter-jordan-brand-video" width="270" height="170" class="alignnone size-full wp-image-73989" /></a>';
$regexp = "<img[^']*?src=\"([^']*?)\"[^']*?>";
if(preg_match_all("/$regexp/siU", $input, $matches)) {
var_dump($matches[1]);
}
$input$='';
$regexp=“”;
if(preg_match_all(“/$regexp/siU”,$input,$matches)){
var_dump($matches[1]);
}
一种非常粗糙的解决方案。。。差不多
$s='<a href="http://heartymagazine.com/wp-content/uploads/2014/07/watch-derek-jeter-jordan-brand-video.png"><img src="http://heartymagazine.com/wp-content/uploads/2014/07/watch-derek-jeter-jordan-brand-video.png" alt="" title="watch-derek-jeter-jordan-brand-video" width="270" height="170" class="alignnone size-full wp-image-73989" /></a>';
preg_match('@"(http://.*)"@',$s,$m);
echo '<pre>';
echo str_replace(array('"','>'),'',$m[1]);
echo '</pre>';
$s='';
preg_match(“@”(http://.)”@,$s,$m);
回声';
echo str_replace(数组(“”,“>”),“$m[1]);
回声';
从HTML提取信息时,最好使用DOM解析器
一种可能的解决办法:
xpath
查询以查找所有img
标记img
标记的src
属性值$html = '<a href="http://heartymagazine.com/wp-content/uploads/2014/07/watch-derek-jeter-jordan-brand-video.png"><img src="http://heartymagazine.com/wp-content/uploads/2014/07/watch-derek-jeter-jordan-brand-video.png" alt="" title="watch-derek-jeter-jordan-brand-video" width="270" height="170" class="alignnone size-full wp-image-73989" /></a>';
// Long version
$dom = new SimpleXMLElement($html);
$images = $dom->xpath('//img');
$firstImage = $images[0];
$src = $firstImage['src'];
// Short version
$src = (new SimpleXMLElement($html))->xpath('//img')[0]['src'];
http://heartymagazine.com/wp-content/uploads/2014/07/watch-derek-jeter-jordan-brand-video.png