从符合模式的PHP存储桶中检索图像(PHP)

时间:2015-05-28 16:32:39

标签: php regex amazon-s3 preg-match

我有一个装满图像的S3存储桶,其命名遵循一个简单的模式。前6位数字按照列表编号分组,尾随数字是非连续的,但遵循可靠的模式(0到99)我正在捕获变量$ln中启动文件名的六位数字。

/*
https://s3.amazonaws.com/stroupenwmls2/602665_10.jpg
https://s3.amazonaws.com/stroupenwmls2/602665_12.jpg
https://s3.amazonaws.com/stroupenwmls2/602665_13.jpg
https://s3.amazonaws.com/stroupenwmls2/602665_15.jpg
*/

我想要做的是用图片的url填充'listing'img src属性,如果该列表存在(如果没有,我提供no-image.jpg)。我正在通过许多不同的列表循环来创建我的网页。

我正在努力获取与$ listing变量匹配的第一张图片的逻辑。这是我尝试过的,没有运气(只产生0):

$bucket = 'https://s3.amazonaws.com/stroupenwmls2/';
$ln = '602665';
$string = $bucket . $ln . '_';
// match the pattern '_xx.jpg', with 1 or 2 numbers
$image = preg_match('/^_[0-9]{1,2}\.(jpg|jpeg|png|gif)/i', $string);

然后在我的网络应用中:

<img src="<?php echo $image ?>">

在使用preg_match时,我是个白痴,我真正需要的是某种通配符参数。我确定我这么复杂。

1 个答案:

答案 0 :(得分:0)

问题是你没有匹配图像路径,你匹配我认为你打算成为正则表达式的一部分。见下文:

$bucket = 'https://s3.amazonaws.com/stroupenwmls2/';
$ln = '602665';
$re = $bucket . $ln . '_' + '[0-9]{1,2}\.(jpg|jpeg|png|gif)';

// let's say you have an array called img_list;
// loop through each path in the list, searching strings
// that match the regular expression constructed in $re.
// if you find a match, return it.
// you'd probably want to define a function to do this for you,
// and call it with the $listing and array as parameters.

foreach (img_list as $img) {
  // this returns either 0 or 1 depending on match.
  // return the first one, and we're done.
  if (preg_match('/^' . $re . '/i', $img)) {
    return $img;
  }
}
相关问题