Daniel PurPur
Daniel PurPur

Reputation: 529

PHP 7.3 glob pattern to return files if does NOT match pattern

I want to return the list of files that does not match a pattern in a path so I can delete them.

Files are in below directory:

"/var/www/servername/directory/subdir_level1/"

Files that I want to keep are named as such:

"e-Calendar_Test-[date and time here].csv"

They start with "e-Calendar_Test-", have a date in the middle and end with ".csv"

Below pattern matches the above criteria:

glob("/var/www/servername/directory/subdir_level1/e-Calendar_Test*.csv")

I want to return files that do NOT match that. I have tried few things:

"^(?!/var/www/servername/directory/subdir_level1/e-Calendar_Test)*.csv"
"/var/www/servername/directory/subdir_level1/(^(?!e-Calendar_Test))*.csv"

And few more but nothing seems to return what I want.

Upvotes: 0

Views: 379

Answers (2)

AbraCadaver
AbraCadaver

Reputation: 78994

glob doesn't support Regular Expressions. Using a glob pattern, just compute the difference of all files and the files that match your pattern. You can adjust the * with the correct number of ? or whatever for the date:

$result = array_diff(glob("/var/www/servername/directory/subdir_level1/*.csv"),
                     glob("/var/www/servername/directory/subdir_level1/e-Calendar_Test-*.csv"));

Replace *.csv with *.* in the first glob if you want all files regardless of extension.

Upvotes: 1

Emma
Emma

Reputation: 27723

My guess is that maybe an expression similar to,

^\/var\/www\/servername\/directory\/subdir_level1\/(?!e-Calendar_Test[^.\r\n]*).*\.csv$

might be desired here.

Test

$re = '/^\/var\/www\/servername\/directory\/subdir_level1\/(?!e-Calendar_Test[^.\r\n]*).*\.csv$/m';
$str = '/var/www/servername/directory/subdir_level1/e-Calendar_Test2019-1-1-11-11-12.csv
/var/www/servername/directory/subdir_level1/e-Calendar_Test2019-1-1-11-11-12.csv
/var/www/servername/directory/subdir_level1/something_else.csv';

preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);

var_dump($matches);

Output

array(1) {
  [0]=>
  array(1) {
    [0]=>
    string(62) "/var/www/servername/directory/subdir_level1/something_else.csv"
  }
}

If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


Upvotes: 0

Related Questions