创建矢量并获取所有图像?

时间:2011-11-01 20:35:18

标签: php preg-match

我需要一些帮助,在我的文章中提供所有图片。 目前我只使用第一张图片:

$first_img = '';
$mycontent = $row['post_content'];
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $my1content, $matches); 
$first_img = $matches [1] [0];
if(empty($first_img)){ //Defines a default image
$first_img = "/img/default.png";}

这只得到文章中的第一张图片..

所以我需要它,从文章中获取所有图像,并将它们连续显示。

谢谢

1 个答案:

答案 0 :(得分:2)

preg_match_all函数将返回数组匹配,foreach循环就足够了。

http://php.net/manual/en/function.preg-match-all.php

foreach($matches as $val) {
    echo $val;
}

更好的模式:/<img(?:(?!src).)+src="?([^"\']+)/i

要处理多个匹配项,您可以执行以下操作:

$mycontent = '<img something="null" src="ggggg.gif"><br/><img src="bob.jpg">';
$output = preg_match_all('/<img(?:(?!src).)+src="?([^"\']+)/i', $mycontent, $matches, PREG_SET_ORDER); // find all src attributes
foreach($matches as $val) { //loop over <img> tags matches
    echo $val[1];
}