首页 > 解决方案 > php使用包含名称的js文件重命名文件

问题描述

是否可以使用 php 重命名目录中的文件以匹配创建的 js 文件的输出。我从我正在使用的 API 下载了数千张图像,但将我的应用程序切换到了新的 API,并且必须将旧的 imageID 与新的 imageID 匹配。我宁愿批量重命名文件,而不是加载 js 文件来获取新的 id 名称。我在 php 方面的经验很少,所有的教程都是简单的文件重命名,没有比这更复杂的了。

img.js

var img_ar = {
"pid_12685":"2578377",
"pid_12757":"2980444",
"pid_12916":"3056906"
}

当前图像文件名 /images

2578377.png
2980444.png
3056906.png

运行 php 脚本后所需的文件名

pid_12685.png  (old file name 2578377.png)
pid_12757.png  (old file name 2980444.png)
pid_12916.png  (old file name 3056906.png)

标签: php

解决方案


您可以制作一个 php 脚本(在您的网络服务器中不需要),然后通过php your_script.php

在该脚本中,您可以使用scandir获取图像目录中所有图像的数组

然后您必须遍历该数组并使用重命名函数重命名图像


因为我没有看到旧名称编号和新名称编号之间的关系,所以您可以创建一个数组

$names = [
    '2578377.png' => 'pid_12685.png'
    '2980444.png' => 'pid_12757.png'
    '3056906.png' => 'pid_12916.png'
];

然后,在你的循环中rename($imageName, $names[$imageName]);


你可以使用这个脚本:

  1. 将脚本放在您的图像目录中,或更改 $path 变量,以便脚本将使用正确的目录

  2. 更改 $names 以包含所有图像

    <?php
    $path = '.';
    $files = array_diff(scandir($path), ['.', '..']);
    
    $names = [
        '2578377.png' => 'pid_12685.png',
        '2980444.png' => 'pid_12757.png',
        '3056906.png' => 'pid_12916.png'
    ];
    
    foreach($files as $file){
        if(is_file($file) && isset($names[$file])){
            rename($file, $names[$file]);
        }
    }
    
  3. 通过调用脚本php script_name.php


推荐阅读