Include JUST files in scandir array?

前端 未结 6 2011
刺人心
刺人心 2020-12-05 14:19

I have an array I\'m getting back from scandir, but it contains \".\" and \"..\" and I don\'t want it to.

My code:

$indir =         


        
相关标签:
6条回答
  • 2020-12-05 14:48

    You can use this snippet. It returns just files in directory:

    function only_files($dir_element) {
        if (!is_dir($dir_element)) {
            return $dir_element;
        }
    }
    
    function givemefiles($dir) {
        $scanned_dir = scandir($dir);
        return array_filter($scanned_dir, "only_files");
    }
    
    $dir_path = '../pages';
    
    givemefiles($dir_path);
    echo "<pre>";
    var_dump($scanned_dir);
    echo "</pre>";
    
    0 讨论(0)
  • 2020-12-05 14:51

    You can use array_filter.

    $indir = array_filter(scandir('../pages'), function($item) {
        return !is_dir('../pages/' . $item);
    });
    

    Note this filters out all directories and leaves only files and symlinks. If you really want to only exclude only files (and directories) starting with ., then you could do something like:

    $indir = array_filter(scandir('../pages'), function($item) {
        return $item[0] !== '.';
    });
    
    0 讨论(0)
  • 2020-12-05 14:51

    Fastest way to remove dots as files in scandir

    $files = array_slice(scandir('/path/to/directory/'), 2); 
    

    From the PHP Manual

    0 讨论(0)
  • 2020-12-05 14:58

    simply use preg_replace to remove all kind of hidden's file from directory

    $files = array(".", "..", "html", ".~html", "shtml");    
    $newfiles = preg_grep('/^([^.])/', scandir($files));
    
    0 讨论(0)
  • 2020-12-05 14:59

    I am aware erknrio provided an answer for this, but here is a cleaner way of getting an array of files without directories (modified to be more efficient):

    $dirPath = 'dashboard';
    
    $dir = scandir($dirPath);
    
    foreach($dir as $index => &$item)
    {
        if(is_dir($dirPath. '/' . $item))
        {
            unset($dir[$index]);
        }
    }
    
    $dir = array_values($dir);
    
    0 讨论(0)
  • 2020-12-05 15:10

    array_diff will do what you're looking for:

    $indir = scandir('../pages');
    $fileextensions = array(".", "php", "html", "htm", "shtml");
    $indir = array_diff($indir, array('.', '..'));
    $replaceextensions = str_replace($fileextensions, "", $indir);
    

    http://php.net/manual/en/function.array-diff.php

    0 讨论(0)
提交回复
热议问题