我想在一个目录中创建一个以字母"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>';