如何删除除文件名为';无论如何.jpg';在PHP中?
删除所有子文件夹中的所有文件的最快的方法是什么除了那些在PHP中文件名为'whater.jpg'的文件之外?未经测试:如何删除除文件名为';无论如何.jpg';在PHP中?,php,file,directory,filesystems,delete-file,Php,File,Directory,Filesystems,Delete File,删除所有子文件夹中的所有文件的最快的方法是什么除了那些在PHP中文件名为'whater.jpg'的文件之外?未经测试: function run($baseDir) { $files = scandir("{$baseDir}/"); foreach($files as $file) { $path = "{$badeDir}/{$file}"; if($file != '.' && $file != '..') {
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('.');
未经测试:
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('.');
这应该是您要查找的,
$但是
是一个包含异常的数组。
不确定它是否是最快的,但它是目录迭代最常用的方法
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'));
这应该是您要查找的,
$但是
是一个包含异常的数组。
不确定它是否是最快的,但它是目录迭代最常用的方法
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'));
为什么不使用迭代器呢?这是经过测试的:
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');
为什么不使用迭代器呢?这是经过测试的:
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');
你说的最快是什么意思?你想分享的方式慢吗?我不想麻烦使用php,操作系统有更好的选择:查找-name filename-type f-delete关于faster,请看:你说的faster是什么意思?你想分享的方式慢吗?我不想麻烦使用php,操作系统有更好的选项:find-name filename-type f-delete,请参阅:注意在PHP5中添加了
scandir()
。注意在PHP5中添加了scandir()
。非常有趣,谢谢。使用“@unlink”和只使用“unlink”有什么区别?非常有趣,谢谢。使用“@unlink”和仅仅“unlink”有什么区别?