Jack Maessen
Jack Maessen

Reputation: 1864

how to exclude a certain folder when using scandir in php

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)

Upvotes: 1

Views: 2457

Answers (4)

Vinz
Vinz

Reputation: 211

Try :

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

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

It's easier than preg_grep

Upvotes: 1

mudraya
mudraya

Reputation: 99

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") );

Upvotes: 1

Dialex
Dialex

Reputation: 439

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

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

Upvotes: 0

Geoffrey Migliacci
Geoffrey Migliacci

Reputation: 402

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

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

Upvotes: 0

Related Questions