从目录列表中排除特定文件夹


exclude specific folders from dir list

如何排除文件夹列表?和. .其他文件夹,比如这个代码中的'thumbs 2'文件夹。

<?php
//Open directory
$dir = dir("../albums/album2/");
//List files in directory
while (($file = $dir->read()) !== false){
        echo " <center><label class='tablog3a'><img src='../albums/album2/thumbs2/$file'> $file<div style='float: right;'> <a href='album2remove.php?file=".$file."'><img src='images/deletetodo.png' class='clickreverse'></a></div></label></center> ";
}
$dir->close();
?>

在你的循环中你可以做

if (!is_dir($file)) {
   //do your echo 
}

在echo之前的while循环中使用if语句如何?

if ( strcmp($file, "thumbs 2") == 0) {
  continue;
}

这也适用于"."answers".. "

if ( strcmp($file, ".") == 0) {
  continue;
}

请注意"strcmp"是一个精确匹配。你可以用"strpos"或类似的东西替换它,它允许子字符串匹配。

你好,希望我的代码能帮到你:

   $chemin_images = "../albums/album2/";

            // begin view pictures: 
            // ======================
            //echo '<hr>';
            $ext_list = Array("jpg", "jpeg", "bmp", "gif", "png", "tif"); // extensions of picture          
            $listephotos = Array();
            if(file_exists($chemin_images)){
                $dossier = opendir($chemin_images); // open the current folder    
                for($i=0; ($f = readdir($dossier)); $i++){
                    //echo '>';
                    //print_r($f);
                    if($f != "." && $f != ".."){ // is a file                       
                    //echo preg_replace("#(.+)'.(.+)#", "$2", strtolower($f)).'<br>';
                        if(in_array(preg_replace("#(.+)'.(.+)#", "$2", strtolower($f)), $ext_list)){ // if a picture
                            $listephotos[$i] = $f; // add picture
                        }
                    }
                }
                //print_r($listephotos);
                closedir($dossier); // we don't need this folder anymore
                sort($listephotos); // sort by name
                // and now, the view
                $nb_img=1;
                foreach($listephotos as $nom){
                    echo '<div style="width:120px;height:120px; padding:3px;margin:10px;float:left;border:solid black 1px;">';
                        echo '<img src="'.$chemin_images. utf8_encode($nom).'" style="width:100%;height:100%;"/>'; // picture name                  
                    echo '</div>';
                        if($nb_img++==6){ // this part if we want to limit the number of pictures
                            //echo ' ... ';
                            //break;
                        }
                    }
                }

您也可以尝试反向(使用glob),只显示扩展名在{ }:

中的文件。
// Show only php and txt files
foreach (glob("*.{php,txt}", GLOB_BRACE) as $filename) {
    echo $filename . '<br />';
}