3

if I have a directory, where a list of file looks like this:

Something_2015020820.txt
something_5294032944.txt.a
something_2015324234.txt
Something_2014435353.txt.a

and I want to get the list of file sort by oldest date (not the filename) and the result should take anything that match something_xxxxxxx.txt. So, anything that ends with ".a" is not included. in this case it should return

Something_2015020820.txt
something_2015324234.txt

I do some google search and it seems like I can use glob

$listOfFiles = glob($this->directory . DIRECTORY_SEPARATOR . $this->pattern . "*");

but I'm not sure about the pattern.

It would be awesome if you could provide both case sensitive and insensitive pattern. The match pattern will have to be something_number.txt

Harts
  • 4,023
  • 9
  • 54
  • 93

2 Answers2

6

It's a bit tricky using glob. It does support some limited pattern matching. For example you can do

glob("*.[tT][xX][tT]");

This will match file.txt and file.TXT, but it will also match file.tXt and file.TXt. Unfortunately there is no way to specify something like file.(txt or TXT). If that's not a problem, great! Otherwise, you'll have to first use this method to at least narrow the results down, and then perform some additional processing afterwards. array_filter and some regex maybe.

A better option might be to use PHP's Iterator classes, so you can specify much more advanced rules.

$directoryIterator = new RecursiveDirectoryIterator($directory);
$iteratorIterator = new RecursiveIteratorIterator($directoryIterator);
$fileList = new RegexIterator($iteratorIterator, '/^.*\.(txt|TXT)$/');
foreach($fileList as $file) {
    echo $file;
}
rjdown
  • 9,162
  • 3
  • 32
  • 45
4

You can use the scandir to get all your files. Then preg_match to filter those files down to ones that don't end with .a. Then filemtime can be used to pull the time the file was last modified. array_multisort can then be used to sort by the time the file was last modified and maintain the key/filename association.

This works as I expected:

date_default_timezone_set('America/New_York'); //change to your timezone
$directory = 'Your Directory';
$files = scandir($directory);
foreach($files as $file) {
    if(!preg_match('~\.a$~', $file) && !is_dir($directory . $file)) {
        $time["$file"] = filemtime($upload_directory . $file);
    }
}
array_multisort($time);

Then to handle the outputting you could do something like:

foreach($time as $file => $da_time){
    echo $file . ' '. date('m/d/Y H:i:s', $da_time) . "\n";
}

The preg_match can have i added after the ~ delimiter so the regex is case insensitive; or you could just make change the a to [aA].

chris85
  • 23,846
  • 7
  • 34
  • 51