Provide two php codes that use traversal to modify the file names of files in batches. Friends in need can refer to them.
Example 1
代码如下 | 复制代码 |
//利用PHP目录和文件函数遍历用户给出目录的所有的文件和文件夹,修改文件名称 function fRename($dirname){ if(!is_dir($dirname)){ echo "{$dirname}不是一个有效的目录!"; exit(); } $handle = opendir($dirname); while(($fn = readdir($handle))!==false){ if($fn!='.'&&$fn!='..'){ $curDir = $dirname.'/'.$fn; if(is_dir($curDir)){ fRename($curDir); } else{ $path = pathinfo($curDir); $newname = $path['dirname'].'/'.rand(0,100).'.'.$path['extension']; rename($curDir,$newname); echo $curDir.'---'.$newname." "; } } } } //给出一个目录名称调用函数 fRename('pl'); ?> |
Example 2
The code is as follows
|
Copy code | ||||
if ($dh = opendir($dir)) {
While (($file = readdir($dh)) !== false) {
If ($file == "." || $file == "..") continue;
If(filetype($dir . $file) == 'file')
{
$newfile = str_replace('[1]', '', $file);
rename($dir . $file, $dir . $newfile);
}
}
closedir($dh);
}