在PHP目录列表中列出某些扩展


Listing certain extensions in PHP Dir List

使用以下内容在数组中提供目录列表

for($index=0; $index < $indexCount; $index++) {
        if (substr("$dirArray[$index]", 0, 1) != ".") { // don't list hidden files
 echo "<option value='"".$dirArray[$index]."'">".$dirArray[$index]."</option>";
 }

有没有什么方法可以修改上面的代码,只显示.JPG和.PNG?

谢谢!

CP

foreach($dirArray[$index] as $k => $v) {
     if(in_array(pathinfo($v, PATHINFO_EXTENSION), array('jpg', 'png', 'jpeg')) {
         echo '<option value="'.$v.'">'.$v.'</option>';
     }
}

我对你的文件数组做了一些假设。你不使用readdir()函数也是有原因的吗?

如果文件名以.jpg.png 结尾,则可以使用正则表达式进行匹配

for($index=0; $index < $indexCount; $index++) 
{
    if(preg_match("/^.*'.(jpg|png)$/i", $dirArray[$index]) == 1) 
    {
      echo "<option value='"".$dirArray[$index]."'">".$dirArray[$index]."</option>";
    }
}

正则表达式末尾的/i是不区分大小写的标志。

for($index=0; $index < $indexCount; $index++) {
        if (substr($dirArray[$index], 0, 1) != "." 
            && strtolower(substr($dirArray[$index], -3)) == 'png' 
            && strtolower(substr($dirArray[$index], -3)) == 'jpg')
            echo '<option value="'.$dirArray[$index].'">'.$dirArray[$index].'</option>';
 }

这应该是可行的,但有更优雅的解决方案,比如使用DirectoryIterator(请参阅此处):

foreach (new DirectoryIterator('your_directory') as $fileInfo) {
    if($fileInfo->isDot() 
        || !in_array($fileInfo->getExtension(), array('png', 'jpg'))) 
        continue;
    echo sprintf('<option value="%s">%s</option>', 
        $fileInfo->getFilename(), 
        $fileInfo->getFilename());
}

未经测试的代码,您可能需要对其进行一些处理。