preg_match_all函数用于从url获取图像(具有特定的exitension和width-height)

时间:2012-04-10 05:38:57

标签: php html regex image preg-match-all

首先,我对PHP更新鲜。 我正在使用以下PHP表达式来获取给定URL的所有图像。

@preg_match_all("<img.+?src=[\"'](.+?)[\"'].+?>", $homepage, $matches, PREG_SET_ORDER);

但是这个表达式也可以使用gif图像获取所有图像。也是1KB大小的图像。

我想要获取最小宽度为100px&amp;的图像。扩展名应为.png / .jpg

如果有人,请提供解决方案。

由于

2 个答案:

答案 0 :(得分:2)

使用array_mapgetimagesize未经测试:

// the domain is needed to get the width of the image
define('DOMAIN', 'http://test.com');

function checkSize($imagename) {
    $info = getimagesize(DOMAIN . $imagename[1]);
    if ($info[0] >= 100000) {
        return $imagename;
    }
}

$homepage = '<img src="test1.png"><img src="test2.gif"><img src="test3.jpg">';
// get all img-tags ending with "jpg" or "png"
preg_match_all("<img.+?src=[\"']([^\"]*\.(jpg|png))[\"'].+?>", $homepage, $matches, PREG_SET_ORDER);
// filter only images with width greater or equal 100k
$images = array_map('checkSize', $matches);

答案 1 :(得分:1)

preg_match_all('~<img(.*?)((src=("|\')(.*?)(jpg|png)("|\'))(.*?)(width=("|\')[0-9]{3,}("|\'))|(width=("|\')[0-9]{3,}("|\'))(.*?)(src=("|\')(.*?)(jpg|png)("|\')))(.*?)>~i',trim($string),$matches);

$yourImagesArray = $matches[0];

我认为这应该可以工作=)至少它适用于我用于测试的每个img标签,它在width-attribute中有一个数字作为值。

/编辑:最好阅读:

$src = '(src=("|\')(.*?)(jpg|png)("|\'))';
$width = '(width=("|\')[0-9]{3,}("|\'))';

preg_match_all('~<img(.*?)('.$src.'(.*?)'.$width.'|'.$width.'(.*?)'.$src.')(.*?)>~i',trim($string),$matches);

$yourImagesArray = $matches[0];