批量重命名文件夹中的文件 - PHP
我在一个文件夹中有1000个图像,在所有图像中都有SKU#字。对于例子批量重命名文件夹中的文件 - PHP
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
完成这个步骤很简单:
- 叠代使用
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);
}
这段代码效果很好,但它也重命名了文件的扩展名。你能解决吗? – 2015-01-22 07:18:03
好,使用迭代器:
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);
}
小菜一碟:
foreach (array_filter(glob("$dir/WV1716B*.jpg") ,"is_file") as $f)
rename ($f, str_replace("SKU#", "", $f));
然后你要做的就是迭代,使用
新
GlobIterator声明一个新的名称,重命名文件...
还是在5.3+
(或$dir/*.jpg
如果数量并不重要)
= 1更简单的解决方案。编辑:`array_filte`r将第一个参数作为数组。 – diEcho 2013-03-20 12:25:04
您也可以使用此示例:
$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));
}
}
你的意思是类似于重命名所有文件的循环? – 2011-02-14 14:58:39