duanbinren8906 2014-06-04 21:07
浏览 34
已采纳

PHP:如何遍历目录并排除数组中出现的任何内容

I have a code that lists all of the files and folders in a directory. What I can't figure out is how to exclude certain files based on a list of values in an array. For instance, I have an array like the one below. I want to reference this list and exclude any item that contains one of those substrings:

$hideDir = array('.php', '.html', '.css');

Here's my current loop. Any thoughts on what I'm doing wrong?

echo '<ul>';
foreach($hideDir as $v) {
if ($handle = opendir('.')) {
    while (false !== ($entry = readdir($handle))) { 
        if (strpos($entry, $v) > -1) {
            //do nothing
        }else{
            echo '<li>' . "$entry" . '</li>' . "
";
        }
    }
}
closedir($handle);
}
echo '</ul>';
  • 写回答

1条回答 默认 最新

  • douye9822 2014-06-04 21:12
    关注

    You're close, but you should drop the whole foreach. Just check while reading the dir, whether the current entry's extension (that can be checked with pathinfo()) is in the array, using in_array():

    echo '<ul>';
    if ($handle = opendir('.')) {
        while (false !== ($entry = readdir($handle))) {
            // Get entry info
            $entryInfo = pathinfo(__DIR__ . DIRECTORY_SEPARATOR . $entry);
    
            // Is this a "hidden" extension?
            if (in_array($entryInfo['extension'], $hideDir)) {
                // Skip it!
                continue;
            }            
    
            // Otherwise, just list it
            echo '<li>' . "$entry" . '</li>' . "
    ";
        }
    }
    closedir($handle);
    echo '</ul>';
    

    Notice that the extension does not contain the dot in front of it, so it should be:

    $hideDir = array('php', 'html', 'css');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥15 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)