我在一个文件夹中有1000张图片,所有图片中都有SKU#word。例如
WV1716BNSKU#.zoom.1.jpg
WV1716BLSKU#.zoom.3.jpg
我需要做的是读取所有文件名并将其重命名为以下
WV1716BN.zoom.1.jpg
WV1716BL.zoom.3.jpg
所以从文件名中删除SKU#,PHP中是否可以进行批量重命名?
答案 0 :(得分:26)
是的,只需打开目录并创建一个循环来访问所有图像并重命名它们,如:
<?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
答案 1 :(得分:10)
小菜一碟:
foreach (array_filter(glob("$dir/WV1716B*.jpg") ,"is_file") as $f)
rename ($f, str_replace("SKU#", "", $f));
(如果数字无关紧要,则为$dir/*.jpg
)
答案 2 :(得分: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#
的文件。然后你要做的就是迭代,声明一个新名称,然后重命名文件......
或使用新 GlobIterator:
在5.3+中$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);
}
答案 3 :(得分:1)
完成此操作的步骤非常简单:
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);
}
答案 4 :(得分: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));
}
}