php - Rename files with its directory name -
i have directories files like:
folder1/filename.jpg folder2/filename.pdf folder3/filename.jpg
and want rename files inside directories corresponding directory name (but keeping extension), like:
folder1/filename.jpg folder1/folder1.jpg folder2/filename.pdf folder2/folder2.pdf folder3/filename.jpg folder3/folder3.jpg
edit: also, want copy renamed files directory (like "allfiles").
i found a similar question in perl language.
how achieve php?
here have way that:
<?php // array subdirectories in directory $dirarray = array_filter(glob('/path/to/directory/*'), 'is_dir'); // $dir path subdirectory foreach ($dirarray $dir) { // $dirname has future name of files in subdirectory $dirname = basename($dir); // take elements in subdirectory (except '.' , '..') $filesarray = array_diff(scandir($dir), array('.', '..')); $i = 0; foreach ($filesarray $file) { // take file extension rename method $fileextension = pathinfo($file, pathinfo_extension); $oldname = $dir . "/" . $file; $newname = $dir . "/" . $dirname . "-" . $i . "." . $fileextension; rename($oldname, $newname); $i++; } }
if sure have 1 file in each subdirectory can use line $newname
:
$newname = $dir . "/" . $dirname . "." . $fileextension;
Comments
Post a Comment