2011-02-14 124 views
9

我在一個文件夾中有1000個圖像,在所有圖像中都有SKU#字。對於例子批量重命名文件夾中的文件 - PHP

WV1716BNSKU#.zoom.1.jpg 
WV1716BLSKU#.zoom.3.jpg 

我需要做的是閱讀所有的文件名,並重新命名爲以下

WV1716BN.zoom.1.jpg 
WV1716BL.zoom.3.jpg 

所以從文件名中刪除SKU#是什麼,是否有可能在PHP做批量重命名?

+0

你的意思是類似於重命名所有文件的循環? – 2011-02-14 14:58:39

回答

1

完成這個步驟很簡單:

  • 疊代使用fopen每個文件,readdir
  • 每個文件解析的文件名成段
  • 舊的文件複製到一個新的直接調用老(理智的原因)
  • 將根文件重新命名爲新名稱。

一個小例子:

if ($handle = opendir('/path/to/images')) 
{ 
    /* Create a new directory for sanity reasons*/ 
    if(is_directory('/path/to/images/backup')) 
    { 
     mkdir('/path/to/images/backup'); 
    } 

    /*Iterate the files*/ 
    while (false !== ($file = readdir($handle))) 
    { 
      if ($file != "." && $file != "..") 
      { 
       if(!strstr($file,"#SKU")) 
       { 
        continue; //Skip as it does not contain #SKU 
       } 

       copy("/path/to/images/" . $file,"/path/to/images/backup/" . $file); 

       /*Remove the #SKU*/ 
       $newf = str_replace("#SKU","",$file); 

       /*Rename the old file accordingly*/ 
       rename("/path/to/images/" . $file,"/path/to/images/" . $newf); 
      } 
    } 

    /*Close the handle*/ 
    closedir($handle); 
} 
+0

這段代碼效果很好,但它也重命名了文件的擴展名。你能解決嗎? – 2015-01-22 07:18:03

2

好,使用迭代器:

class SKUFilterIterator extends FilterIterator { 
    public function accept() { 
     if (!parent::current()->isFile()) return false; 
     $name = parent::current()->getFilename(); 
     return strpos($name, 'SKU#') !== false; 
    } 
} 
$it = new SkuFilterIterator(
    new DirectoryIterator('path/to/files') 
); 

foreach ($it as $file) { 
    $newName = str_replace('SKU#', '', $file->getPathname()); 
    rename($file->getPathname(), $newName); 
} 

的FilterIterator基本上過濾掉所有的非文件和文件,而其中的SKU#

$it = new GlobIterator('path/to/files/*SKU#*'); 
foreach ($it as $file) { 
    if (!$file->isFile()) continue; //Only rename files 
    $newName = str_replace('SKU#', '', $file->getPathname()); 
    rename($file->getPathname(), $newName); 
} 
9

小菜一碟:

foreach (array_filter(glob("$dir/WV1716B*.jpg") ,"is_file") as $f) 
    rename ($f, str_replace("SKU#", "", $f)); 
然後你要做的就是迭代,使用 GlobIterator聲明一個新的名稱,重命名文件...

還是在5.3+

(或$dir/*.jpg如果數量並不重要)

+0

= 1更簡單的解決方案。編輯:`array_filte`r將第一個參數作爲數組。 – diEcho 2013-03-20 12:25:04

1

您也可以使用此示例:

$directory = 'img'; 
$gallery = scandir($directory); 
$gallery = preg_grep ('/\.jpg$/i', $gallery); 
// print_r($gallery); 

foreach ($gallery as $k2 => $v2) { 
    if (exif_imagetype($directory."/".$v2) == IMAGETYPE_JPEG) { 
     rename($directory.'/'.$v2, $directory.'/'.str_replace("#SKU","",$v2)); 
    } 
}