PHP Unlink()可以根据模式删除多个文件吗?

问题描述 投票:-1回答:2

我想知道unlink()函数是否可以根据模式删除多个文件,例如:

unlink('./directory/(*).txt');

是否有类似的东西删除多个文件(例如.txt文件)而不需要glob()和循环?

php unlink
2个回答
0
投票

不,但这只有77个字节或69个单字母变量:

array_map('unlink',preg_filter('/^/',$dir,preg_grep($regex,scandir($dir))));
//array_map('unlink',preg_filter('/^/',$d,preg_grep($r,scandir($d))));

未经测试,应该在理论上工作(也许)。 $dir是带有结尾斜杠的目录。 $regex是一个完整的正则表达式。

不需要glob()和循环

没有水珠,没有循环。虽然我确实使用过array_map但我没有关闭它。

用于检测:

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

产量

//these would be sent to unlink
Array
(
    [0] => somefolder/index.php
    [2] => somefolder/somefile.php
)

Sandbox

干杯!


0
投票

documentation说你只能传递一个文件,就像C的unlink一样。

© www.soinside.com 2019 - 2024. All rights reserved.