Bulk Rename Files in a Folder - PHP

后端 未结 5 1483
日久生厌
日久生厌 2020-12-02 21:23

I have 1000 images in a Folder, which has SKU# word in all the images. For examples

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

what i

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-02 21:49

    The steps to completing this is pretty simple:

    • iterate over each file using fopen, readdir
    • for each file parse the file name into segments
    • copy the old file into a new directly called old (sanity reasons)
    • rename the root file top the new name.

    A small example:

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

提交回复
热议问题