Hongmu Notes
Home Language Notes PHP batch replaces file names in specified folders
Language Notes PHP

PHP batch replaces file names in specified folders

PHP batch replaces file names in specified folders

Here is a PHP function that allows for batch renaming of files within a specified folder:

 隐藏内容:登录后可查看
function batchRenameFiles($dir, $search, $replace) {
  $files = scandir($dir); // 获取目录下所有文件

  foreach ($files as $file) {
    $filePath = $dir . DIRECTORY_SEPARATOR . $file;

    // 排除 "." 和 ".." 以及目录
    if ($file == '.' || $file == '..' || is_dir($filePath)) {
      continue;
    }

    // 检查文件名是否包含搜索字符串
    if (strpos($file, $search) !== false) {
      $newName = str_replace($search, $replace, $file); // 构造新文件名

      // 检查新文件名是否已存在
      if (file_exists($dir . DIRECTORY_SEPARATOR . $newName)) {
        echo "文件 $newName 已存在,跳过文件 $file。\n";
      } else {
        // 进行文件重命名
        if (rename($filePath, $dir . DIRECTORY_SEPARATOR . $newName)) {
          echo "重命名文件 $file 为 $newName 成功。\n";
        } else {
          echo "重命名文件 $file 为 $newName 失败。\n";
        }
      }
    }
  }
}

This function accepts three parameters:

  • $dirSpecify the directory path for batch renaming of files.
  • $searchThe string to search for and replace.
  • $replaceThe string to be replaced.

The function is used. scandir The function retrieves all files within a specified directory, then checks each file; if the file name contains the search string, it constructs a new file name and performs a renaming operation. During this renaming process, the function also checks whether the new file name already exists to avoid naming conflicts.

You can call this function using the following methods:

batchRenameFiles('/path/to/directory', 'old_string', 'new_string');

among,/path/to/directory The directory path for batch renaming.old_string The string to search for and replace,new_string The string to be replaced.

Successful rendering result:

ad1a1b7183091948

You can tweak the output a bit – just add a <br> tag.

微信赞赏

WeChat

支付宝赞赏

Alipay

✍️ Author: Hong Mu

webmaster · Thanks for reading, stay tuned for more exciting content

Author homepage View home page →

Related articles

PHP ob function record

PHP ob function record Language Notes PHP

Usage of the following three functions ob_get_contents(); ob_end_clean(); ob_start(); You can use these functions to buffer local files and execute local script code. Use ob_start() to save the output code into the buffer, and the page will not be displayed; then use ob_get_contents to get the data in the buffer. o…
👁 141
PHP preg

PHP preg Language Notes PHP

The preg_match_all function is used to perform a global regular expression match. preg_match_all() Syntax int preg_match_all ( string $pattern , string $subject [, array &$matches [, int $flags = PREG…
👁 169
Detailed explanation of PHP ternary operator and if

Detailed explanation of PHP ternary operator and if Language Notes PHP

Ternary operator condition ? Result 1 : Result 2 Explanation: The position in front of the question mark is the condition for judgment. If the condition is met, the result is 1, and if it is not met, the result is 2. This article compares and explains the ternary operator and if...else... in detail. I hope it will be helpful to everyone. Today when I was revising my paper online, I encountered a statement that I couldn’t understand: $if_summary = $row['IF_SUMMARY']=…
👁 189
PHP cast type

PHP cast type Language Notes PHP PHP collection PHP and mysql

Get the data type 1. If you want to check the value and type of an expression, use var_dump(). 2. If you just want to get an easy-to-read type expression for debugging, use gettype(). 3. To check a certain type, do not use gettype(), but use the is_type() function. Converting Strings to Numbers When a string is evaluated as a number, the result is determined according to the following rules...
👁 232

Recommended reading

PHP function to delete all files and directories within a specified directory; allows for excluding certain files.

PHP function to delete all files and directories within a specified directory; allows for excluding certain files. Language Notes PHP

I really cried! After a lot of troubleshooting, I realized that the `glob` function was a bit tricky to use – it didn't let me retrieve the files properly. Then, I looked into the system's hidden files, and after more digging, I discovered that there were other functions available to query all files! In PHP, you can delete all files and directories within a specified directory using a function with two parameters: one for the directory to be deleted and another for an array of files that should not be deleted. The function is: `function deleteDirectory($direc...`
👁 179
(Adaptive mobile version) Outdoor sports equipment website PBootCMS template; Sports apparel website source code download – 0350

(Adaptive mobile version) Outdoor sports equipment website PBootCMS template; Sports apparel website source code download – 0350 Practical Collection pbootcms Template

An adaptive mobile-friendly outdoor sports equipment and athletic wear website template based on PbootCMS. The design features a dynamic, sports-oriented style, ideal for showcasing outdoor gear, athletic apparel, and brand stories. It helps sports goods brands attract sports enthusiasts online and enhance their brand image. Template Preview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn...
👁 49
Lighting and Home Decor Website Template 0260

Lighting and Home Decor Website Template 0260 Practical Collection Yiyou template

An EyouCMS website template designed for the lighting and home decoration industry. Its modern, bright design is ideal for showcasing lighting products, home decor items, lighting solutions, and brand stories. This template helps lighting brands showcase their products online and attract both residential and commercial clients. Template Preview | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS...
👁 33
JavaScript close this page after three seconds

JavaScript close this page after three seconds Language Notes JavaScript

可以使用 JavaScript 中的 setTimeout() 函数来实现页面自动关闭的效果。 The following is a sample code: setTimeout(function() { window.close(); }, 3000); In this code, the setTimeout() function will call an anonymous function after 3 seconds, and the anonymous function will call...
👁 193
(Adaptive mobile version) PBootCMS template for mobile app download websites; Source code download for game software application websites – 0351

(Adaptive mobile version) PBootCMS template for mobile app download websites; Source code download for game software application websites – 0351 Practical Collection pbootcms Template

This is an adaptive mobile-friendly PbootCMS website template designed for downloading mobile games and applications – ideal for showcasing download links and product descriptions. It helps software download sites attract online traffic and generate ad revenue. Template Preview | Installation Instructions | Website Backend: /admin.php | Username: admin | Password: admin | Extraction Password: www.4s5.cn | Related Articles...
👁 55
Beauty, Makeup & Weight Loss Website Template 0261

Beauty, Makeup & Weight Loss Website Template 0261 Practical Collection Yiyou template

This EyouCMS template is ideal for the beauty, makeup, and weight loss industries. Its stylish and sophisticated design is perfect for showcasing beauty services, makeup and styling services, weight loss programs, and brand stories. It helps beauty and weight loss establishments attract female customers online and enhance their brand awareness. Template Display | Installation Instructions | Website Backend: /login.php | Username: admin | Password: admin | Related Articles: Summary of Common Installation Issues for EyouCMS | EyouCMS...
👁 34