Home  >  Article  >  Backend Development  >  How to batch rename files in php

How to batch rename files in php

王林
王林Original
2020-10-22 18:04:562594browse

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);] .

How to batch rename files in php

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__.&#39;./color/&#39;;
$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(&#39;color_%02s&#39;, $i + 1);
    $old_file_name = $dir.$file_arr[$i];
    $new_file_name = $title.strrchr($file_arr[$i],&#39;.&#39;);
    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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn