在文件夹中批量重命名文件 - PHP

18

我有一个包含1000张图片的文件夹,所有这些图片上都带有SKU#字样,例如:

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

我需要做的是读取所有文件名并将其重命名为以下内容

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

如何在PHP中进行批量重命名以从文件名中删除SKU#?


你的意思是像循环一样重命名所有文件吗? - Michiel Pater
6个回答

41

是的,只需打开目录并创建一个循环来访问所有图像并重命名它们,例如:

<?php

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

参考资料:

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

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

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


12

易如反掌:

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

(或者如果数量不重要,则为$dir/*.jpg


array_filter的第一个参数应该是数组。如果您想要更简单的解决方案,请将其设为1。 - xkeshav
glob通常比目录迭代慢几倍 - 因此,如果您有很多文件 - 这是需要考虑的事情:https://www.phparch.com/2010/04/putting-glob-to-the-test/ - Picard

3
完成这个过程的步骤非常简单:
  • 使用fopenreaddir迭代每个文件
  • 对于每个文件,将文件名解析为各个片段
  • 将旧文件复制到名为old的新目录中(出于安全考虑)
  • 将根文件重命名为新名称。
以下是一个简单的示例:
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);
}

这段代码运行良好,但它也重命名了文件的扩展名。你能解决吗? - Syed Ibrahim

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#的文件。然后你只需要进行迭代,声明一个新名称,并重命名这个文件...

或者在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);
}

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接