我有一个博客条目,其中有多个图像(有时一个,有时两个,有时三个),看起来有点像这样:
<a href="http://xxx/" rel="attachment w133>
<img class="yyy" title="title1" src="http://xxx/title1.jpg" alt="" width="650" height="487" />
</a>
<a href="http://xxx/" rel="attachment w134">
<img class="yyy" title="title2" src="http://xxx/title2.jpg" alt="" width="650" height="487" />
</a>
<a href="http://xxx/" rel="attachment w135">
<img class="yyy" title="title3" src="http://xxx/title3.jpg" alt="" width="650" height="487" />
</a>
后面有一些文字。
现在,我想知道如何使用preg_match_all来提取第一部分。我现在有点关于PHP编程,但从未使用过preg_match_all。
这里的代码确实只提取了最后一张图片,这还不够:
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post_content, $matches);
如果有人可以给我一个提示如何实现这一目标,如果可能的话,那就太棒了。非常感谢!
答案 0 :(得分:3)
$post_content='<a href="http://xxx/" rel="attachment w133>
<img class="yyy" title="title1" src="http://xxx/title1.jpg" alt="" width="650" height="487" />
</a>
<a href="http://xxx/" rel="attachment w134">
<img class="yyy" title="title2" src="http://xxx/title2.jpg" alt="" width="650" height="487" />
</a>
<a href="http://xxx/" rel="attachment w135">
<img class="yyy" title="title3" src="http://xxx/title3.jpg" alt="" width="650" height="487" />
</a>
';
preg_match_all('/<a\s[^>]*href=([\"\']??)([^\" >]*?)\\1[^>]*>(.*)<\/a>/siU', $post_content, $matches);
//print_r ($matches);//$matches - array which contains all your images
print $matches[0][0]; //first link with image
print $matches[0][1]; //second link with image
print $matches[0][2]; //third link with image
输出:
<a href="http://xxx/" rel="attachment w133>
<img class=" yyy"="" title="title1" src="http://xxx/title1.jpg" alt="" width="650" height="487">
</a>
<a href="http://xxx/" rel="attachment w134">
<img class="yyy" title="title2" src="http://xxx/title2.jpg" alt="" width="650" height="487">
</a>
<a href="http://xxx/" rel="attachment w135">
<img class="yyy" title="title3" src="http://xxx/title3.jpg" alt="" width="650" height="487">
</a>
答案 1 :(得分:0)
尝试:
preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"][^\/>]*>/Ui', $post_content, $matches);
print_r($matches);