2012-07-17 174 views
1

什麼是刪除所有文件所有子文件夾除了那些文件名是「whatever.jpg」在PHP中最快方法是什麼?如何刪除除PHP文件名爲'whatever.jpg'以外的所有子文件夾中的所有文件?

+0

你是什麼意思**最快**? – Teneff 2012-07-17 20:13:29

+2

你有沒有想要分享的緩慢方式? – 2012-07-17 20:14:49

+2

我不打擾使用PHP,操作系統有更好的選擇:發現! -name filename -type f -delete – 2012-07-17 20:18:07

回答

3

爲什麼不使用迭代器?這是測試:

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'); 
+0

非常有趣,謝謝。使用「@unlink」和「取消鏈接」有什麼區別? – ProgrammerGirl 2012-07-17 23:48:38

+0

@取消由該語句生成的任何錯誤消息。 – Dreen 2012-07-18 00:15:24

+0

這是一個很好的 – Ron 2012-07-18 07:26:54

0

未經測試:

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('.'); 
+0

這是不好的代碼 - 樣式。希望linus沒有看到這個^^ – Ron 2012-07-17 20:17:38

+0

注意'scandir()'是在PHP5中添加的。 – Dreen 2012-07-17 20:28:24

1

這應該是什麼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')); 
相關問題