how to exclude a certain folder when using scandir in php

2k Views Asked by At

I am using scandir to list all the files in a directory. But there should be an exception for ./, ../ and tmp folder.

I already have this to exclude the dot and double dot:

$files = preg_grep('/^([^.])/', scandir($dir));

How can i add tmp folder to it? (name of the folder is tmp)

4

There are 4 best solutions below

0
Vinz On

Try :

   $toRemove = array('.','..','tmp'); 

   $cdir = scandir($dir);
   
   $result = array_diff($cdir, $toRemove);

It's easier than preg_grep

0
Geoffrey Migliacci On

Since it's a regex you can try to take a look at the negative lookahead:

$files = preg_grep('/^(?!tmp|\.{1,2})$/', scandir($dir));
0
Dialex On

I would have done something like that if you want to stick with regex

$files = preg_grep('/^(?!tmp|(?!([^.]))).*/', scandir($dir));

1
mudraya On

I would choose for this solution, because of already mentioned by @duskwuff, your current code excludes all the files which start with a .

$files = array_diff( scandir($dir), array(".", "..", "tmp") );