簡體   English   中英

批量重命名文件夾中的文件 - PHP

[英]Bulk Rename Files in a Folder - PHP

我在一個文件夾中有 1000 張圖片,所有圖片中都有 SKU# 字樣。 舉些例子

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

我需要做的是讀取所有文件名並將其重命名為以下

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

那么從文件名中刪除 SKU#,是否可以在 PHP 中進行批量重命名?

是的,只需打開目錄並創建一個循環來訪問所有圖像並重命名它們,例如:

<?php

if ($handle = opendir('/path/to/files')) {
    while (false !== ($fileName = readdir($handle))) {
        $newName = str_replace("SKU#","",$fileName);
        rename($fileName, $newName);
    }
    closedir($handle);
}
?>

參考:

http://php.net/manual/en/function.rename.php

http://php.net/manual/en/function.readdir.php

http://php.net/manual/en/function.str-replace.php

小菜一碟:

foreach (array_filter(glob("$dir/WV1716B*.jpg") ,"is_file") as $f)
  rename ($f, str_replace("SKU#", "", $f));

(或$dir/*.jpg如果數字無關緊要)

完成此操作的步驟非常簡單:

  • 使用fopenreaddir遍歷每個文件
  • 對於每個文件,將文件名解析為段
  • 將舊文件復制到直接稱為舊的新文件中(理智原因)
  • 將根文件重命名為新名稱。

一個小例子:

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

好吧,使用迭代器:

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#的文件。 然后你所做的就是迭代,聲明一個新名稱,然后重命名文件......

或者在 5.3+ 中使用GlobIterator

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

您還可以使用此示例:

$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));
    }
}
$curDir = "/path/to/unprocessed/files";
$newdir = "/path/to/processed/files";

if ($handle = opendir($curDir)) 
{
    //make the new directory if it does not exist
    if(!is_dir($newdir))
    {
         mkdir($newdir);
    }

    //Iterate the files
    while ($file = readdir($handle))
    {
            // invalid files check (directories or files with no extentions)
            if($file != "." && $file != "..")
            {
                //copy
                copy($curDir."/".$file, $newdir."/".$file);
        
                $newName = str_replace("SKU#","",$file); 
                
                //rename
                rename($newdir."/".$file, $newdir."/".$newName.".jpg");
            
            }
    }
    closedir($handle);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM