我希望脚本进入文件夹‘图像’,获取每个文件,剪切前四个字符,并重命名它。
<?php
$path = './images/';
if ($handle = opendir($path))
{
while (false !== ($fileName = readdir($handle)))
{
if($fileName!=".." && $fileName!=".")
{
$newName = substr($fileName, 4);
$fileName = $path . $fileName;
$newName = $path . $newName;
rename($fileName, $newName);
}
}
closedir($handle);
}
?>图像文件夹中的文件是这样命名的:
0,78test-1.jpg
0,32test-2.jpg
0,43test-3.jpg
0,99test-4.jpg这就是我想让他们看起来的样子:
test-1.jpg
test-2.jpg
test-3.jpg
test-4.jpg问题是脚本剪掉了最初的8,12或16个字符,而不是我想要的四个字符!因此,当我执行它时,我的文件如下所示:
-1.jpg
-2.jpg
-3.jpg
-4.jpg更新
我还跟踪了包,以确保我没有多次执行脚本。脚本只执行一次!
发布于 2016-09-27 07:02:51
一种稍微不同的方法,虽然在本质上与substr部分相同,但对于本地系统上的测试来说,效果很好。
$dir='c:/temp2/tmpimgs/';
$files=glob( $dir . '*.*' );
$files=preg_grep( '@(\.jpg$|\.jpeg$|\.png$)@i', $files );
foreach( $files as $filename ){
try{
$path=pathinfo( $filename, PATHINFO_DIRNAME );
$name=pathinfo( $filename, PATHINFO_BASENAME );
$newname=$path . DIRECTORY_SEPARATOR . substr( $name, 4, strlen( $name ) );
if( strlen( $filename ) > 4 ) rename( $filename, $newname );
} catch( Exception $e ){
echo $e->getTraceAsString();
}
}发布于 2016-09-27 06:51:34
你可能想试试这个小功能。它只会对您进行适当的重命名:
<?php
$path = './images/';
function renameFilesInDir($dir){
$files = scandir($dir);
// LOOP THROUGH THE FILES AND RENAME THEM
// APPROPRIATELY...
foreach($files as $key=>$file){
$fileName = $dir . DIRECTORY_SEPARATOR . $file;
if(is_file($fileName) && !preg_match("#^\.#", $file)){
$newFileName = preg_replace("#\d{1,},\d{1,}#", "", $fileName);
rename($fileName, $newFileName);
}
}
}
renameFilesInDir($path);发布于 2016-09-27 07:05:51
<?php
$path = './images/';
if ($handle = opendir($path))
{
while (false !== ($fileName = readdir($handle)))
{
if($fileName!=".." && $fileName!=".")
{
//change below line and find first occurence of '-' and then replace everything before this with 'test' or any keyword
$newName = substr($fileName, 4);
$fileName = $path . $fileName;
$newName = $path . $newName;
rename($fileName, $newName);
}
}
closedir($handle);
}
?>https://stackoverflow.com/questions/39717467
复制相似问题