I want to know if unlink() function can delete multiple files based on a pattern for example:
unlink('./directory/(*).txt');
Is there something like that to delete multiple files (.txt files for example) without the need of glob() and loops?
No, but this is only 77 bytes or 69 with single letter variables:
array_map('unlink',preg_filter('/^/',$dir,preg_grep($regex,scandir($dir))));
//array_map('unlink',preg_filter('/^/',$d,preg_grep($r,scandir($d))));
Untested, should work in theory (Maybe). $dir
is the directory with an ending slash. $regex
is a full Regular expression.
without the need of glob() and loops
No glob, no loop. Although I did use array_map
but I did it without a closure.
For testing:
$dir = 'somefolder/';
//scandir($dir)
$files = ['index.php', 'image.jpg', 'somefile.php'];
//look for files ending in .php
$regex = '/\.php$/';
//strval is useless here but, it shows it works, these are strings so it just returns what we already have
$files = array_map('strval', preg_filter('/^/', $dir, preg_grep($regex, $files)));
//I could have used 'print_r' instead of 'strval' but this is formatted better!
print_r($files);
Output
//these would be sent to unlink
Array
(
[0] => somefolder/index.php
[2] => somefolder/somefile.php
)
Cheers!