Home > Article > Backend Development > How to batch rename files in php
How to rename files in batches in php: first get all the file names in the current directory; then rename the files through a for loop and the rename function, such as [rename($v,$newName);] .
Analysis:
First get all the file names in the current directory;
Then Rename with rename.
(Recommended tutorial: php video tutorial)
Example one:
<?php $list = scandir(__DIR__); foreach ($list as $k => $v){ $newName = str_replace("替换前","替换后",$v); rename($v,$newName); echo $newName; }
Example two:
<?phpheader("Content-type:text/html;charset=utf-8"); $dir = __DIR__.'./color/'; $file_arr = scandir($dir);unset($file_arr[0]);unset($file_arr[1]); $file_arr = array_values($file_arr); $n = count($file_arr);for ($i = 0; $i < $n; ++$i){ $title = sprintf('color_%02s', $i + 1); $old_file_name = $dir.$file_arr[$i]; $new_file_name = $title.strrchr($file_arr[$i],'.'); rename($old_file_name, $new_file_name); }
Related Recommended: php training
The above is the detailed content of How to batch rename files in php. For more information, please follow other related articles on the PHP Chinese website!