我在一个文件夹中有1000张图片,所有图片中都有SKU# word。例如:
WV1716BNSKU#.zoom.1.jpg
WV1716BLSKU#.zoom.3.jpg
我需要做的是读取所有文件名并将其重命名为以下名称
WV1716BN.zoom.1.jpg
WV1716BL.zoom.3.jpg
那么从文件名中删除SKU#,在PHP中可以进行批量重命名吗?
发布于 2011-02-14 22:57: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
http://php.net/manual/en/function.readdir.php
http://php.net/manual/en/function.str-replace.php
发布于 2011-02-14 23:18:30
小菜一碟:
foreach (array_filter(glob("$dir/WV1716B*.jpg") ,"is_file") as $f)
rename ($f, str_replace("SKU#", "", $f));
(如果数量无关紧要,则为$dir/*.jpg
)
发布于 2011-02-14 23:04:41
完成此操作的步骤非常简单:
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);
}
https://stackoverflow.com/questions/4993590
复制相似问题