创建一个包含所有以 'n' - PHP 开头的 jpeg 文件的数组

Create an array of all jpeg files start with 'n' - PHP

我想创建一个目录中所有文件的数组,这些文件以字母 'n' 开头并且是 jpg 或 JPEG 的图像文件。到目前为止我的代码是:

//Get all the files in the products images directory
if ($dir = opendir($uploads)) {
    $images = array();
    while (false !== ($file = readdir($dir))) {
        if ($file != "." && $file != "..") {                  
            foreach (glob("*.jpg") as $filename { 
            $images[] = $filename;
            } 
        }
    }
    closedir($dir);
}

我尝试在 foreach 中添加,但它导致了 500 服务器错误。我是 php 中编码的新手,因此非常感谢任何建议。 此致

唐娜

使用 phps glob(),请参阅 http://php.net/manual/en/function.glob.php 了解详细文档。

// Make sure $uploads has a trailing /
if(substr($uploads, -1) != '/') $uploads .= '/';

// Find all jpg files whose where name starts with "n" regardless of jpg or JPG file extension (all cases are matched)
$images = glob($uploads . 'n*.[jJ][pP]{eg,g,Eg,eG,G}', GLOB_BRACE);

var_dump($images);

编辑:重写,测试。工作正常,无论您的文件是用小写还是大写命名。

请注意,您必须将变量 $uploads 设置为末尾的斜杠。

$uploads = 'uploads/'; // must be with slash at the end

if ($dir = opendir($uploads))
{
  $images = array();

  foreach (glob($uploads."*.{jpg,jpeg,JPG,JPEG}", GLOB_BRACE) as $filename)
  {
    $f = str_replace($uploads, null, $filename);
    if (strtolower($f[0]) == 'n')
    {
      $images[] = $f;
    }
  }
}    

echo '<pre>';
print_r($images);
echo '</pre>';