Bulk Rename Files in a Folder - PHP

后端 未结 5 1476
日久生厌
日久生厌 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条回答
  •  萌比男神i
    2020-12-02 22:14

    Well, using iterators:

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

    The FilterIterator basically filters out all non-files, and files without the SKU# in them. Then all you do is iterate, declare a new name, and rename the file...

    Or in 5.3+ using the new 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);
    }
    

提交回复
热议问题