我有大约600张图像,我想用一个小的PHP代码重命名
我已经尝试过以下链接,并根据自己的意愿对其进行了修改:
rename all the image files in a specified directory
<?php
$dir = 'C:/xampp/htdocs/rename/fotos/all_fotos';
$file = opendir($dir);
$data = readdir($file);
if(is_dir($dir)){
echo $dir . '</br>';
echo $file . '</br>';
echo $data . '</br>';
while(($data = readdir($file)) !== false){
$info = pathinfo($data, PATHINFO_EXTENSION);
if($info=='jpg'){
if(strlen($data)==5){
rename($data, $dir . $data = 3 . substr($data, 0, -4) . '.jpg');
}else if(strlen($data)==6){
rename($data, $dir . $data = substr($data, 0, -4) . '.jpg');
}else{
echo "renaming didn't work, please try again <br/>";
}
}else{
echo 'selected file is not a .jpg extension <br/>';
echo basename(pathinfo($data, PATHINFO_BASENAME),'.jpg') . '</br>';
}
}echo $info;
}else{
echo dirname($dir) . 'wrong directory </br>';
}
closedir($file);
?>
预期的结果将是:“ 12340”变成“ 31234”,如果长度是6,例如:“ 123450”应该变成“ 12345”,但是第一个if中的第二个“ echo $ file” ()部分返回“资源ID#3”
答案 0 :(得分:0)
使用echo和var_dump()更清楚地了解输出可能会很有趣。第一点:rename()函数的两个参数都需要全路径(请参阅官方文档https://www.php.net/manual/fr/function.rename.php)。第二:要获取文件的字符串名称,您需要basename()函数(https://www.php.net/manual/fr/function.basename.php)。第三点:您尚未在strlen ... = 5或strlen ... = 6中考虑扩展名“ .jpg”。最后一点:使用目录的相对路径(相对于您的php renaming-script):
//$dir = 'C:/xampp/htdocs/rename/fotos/all_fotos';
$dir = __DIR__.'/renameimg';
$file = opendir($dir);
$data = readdir($file);
if(is_dir($dir)){
echo '</br>dir : '.$dir;
echo '</br>file : '.$file;
echo '</br>data : '.$data;
while(($data = readdir($file)) !== false){
echo "<br/>";
var_dump($data);
if(is_dir("$dir/$data"))
echo "<br/>Directory: ".$data;
else if(is_file("$dir/$data"))
echo "<br/>File: ".$data;
$info = pathinfo($data, PATHINFO_EXTENSION);
if($info=='jpg'){
$filename = basename($data);
echo "<br/>data length : ". strlen($data);
echo "<br/>filename=basename(data) length : ". strlen($filename);
if(strlen($filename)==9){
rename("$dir/$data", "$dir/3".substr($filename, 0, -4) . '.jpg');
}else if(strlen($filename)==10){
rename("$dir/$data", "$dir/".substr($filename, 0, -4) . '.jpg');
}else{
echo "<br/>Length is not 5 or 6 : renaming didn't work !";
}
}else{
echo 'selected file is not a .jpg extension <br/>';
echo basename(pathinfo($data, PATHINFO_BASENAME),'.jpg').'</br>';
}
}echo $info;
}else{
echo dirname($dir) . 'wrong directory </br>';
}
closedir($file);