【问题标题】:preg_match_all function for getting images(with specific exitension & width-height) from urlpreg_match_all 函数用于从 url 获取图像(具有特定的扩展和宽度-高度)
【发布时间】:2012-04-10 05:38:56
【问题描述】:

首先,我对 PHP 比较陌生。 我正在使用以下 PHP 表达式从给定的 url 获取所有图像。

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

但是这个表达式也会获取所有带有 gif 图像和 1KB 大小的图像的图像。

我想获取最小宽度为 100 像素的图像,扩展名应为 .png/.jpg

如果有人有,请给我一个解决方案。

谢谢

【问题讨论】:

  • HTML 中有没有关于图片大小的提示?
  • 给定的 URL 或网页?
  • 不,没有关于大小的提示..$homepage = @file_get_contents($_POST['url']);
  • 因此显然您必须获取所有图像 URL 并使用 getimagesize() 将远程服务器上图像的 URL 传递给它以检索其大小。也许下载所有图像文件并在本地分析它们会更有效......

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


【解决方案1】:

未经测试使用array_map 和getimagesize:

// 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);

【讨论】:

    【解决方案2】:
    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 标签,这些标签在宽度属性中都有一个数字作为值。

    /编辑:这更好读:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-11
      • 1970-01-01
      • 2014-07-15
      • 2012-04-19
      • 2015-09-04
      • 2016-01-11
      相关资源
      最近更新 更多