如何删除除PHP文件名为'whatever.jpg'以外的所有子文件夹中的所有文件?
为什么不使用迭代器?这是测试:
function run($baseDir, $notThis)
{
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($baseDir), RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
if ($file->isFile() && $file->getFilename() != $notThis) {
@unlink($file->getPathname());
}
}
}
run('/my/path/base', 'do_not_cancel_this_file.jpg');
非常有趣,谢谢。使用“@unlink”和“取消链接”有什么区别? – ProgrammerGirl 2012-07-17 23:48:38
@取消由该语句生成的任何错误消息。 – Dreen 2012-07-18 00:15:24
这是一个很好的 – Ron 2012-07-18 07:26:54
未经测试:
function run($baseDir) {
$files = scandir("{$baseDir}/");
foreach($files as $file) {
$path = "{$badeDir}/{$file}";
if($file != '.' && $file != '..') {
if(is_dir($path)) {
run($path);
} elseif(is_file($path)) {
if(/* here goes you filtermagic */) {
unlink($path);
}
}
}
}
}
run('.');
这应该是什么youre寻找,$but
是一个数组控股例外。 不知道它的是最快的,但它是目录迭代最常用的方式。
function rm_rf_but ($what, $but)
{
if (!is_dir($what) && !in_array($what,$but))
@unlink($what);
else
{
if ($dh = opendir($what))
{
while(($item = readdir($dh)) !== false)
{
if (in_array($item, array_merge(array('.', '..'),$but)))
continue;
rm_rf_but($what.'/'.$item, $but);
}
}
@rmdir($what); // remove this if you dont want to delete the directory
}
}
使用例:
rm_rf_but('.', array('notme.jpg','imstayin.png'));
你是什么意思**最快**? – Teneff 2012-07-17 20:13:29
你有没有想要分享的缓慢方式? – 2012-07-17 20:14:49
我不打扰使用PHP,操作系统有更好的选择:发现! -name filename -type f -delete – 2012-07-17 20:18:07