Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP get list of files matching a pattern and sort by oldest file

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

like image 436
Harts Avatar asked Nov 29 '25 05:11

Harts


1 Answers

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;
}
like image 114
rjdown Avatar answered Dec 01 '25 19:12

rjdown



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!