首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Php中使用regex批量重命名

在Php中使用regex批量重命名
EN

Stack Overflow用户
提问于 2018-06-10 04:29:21
回答 4查看 284关注 0票数 0

我在服务器上有一个文件夹,里面有很多图像,我想重命名一些图像。包含(1的镜像示例:

112345(1.jpg to 112345.jpg。如何在PHP中使用regex执行此操作?我不得不提一下,我对PHP的了解非常有限,它是唯一一种可以有效地编写脚本的语言。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2018-06-10 05:22:19

preg_match('/\(1/', $entry)会帮你的。

此外,您还需要注意“如果文件在重命名后有重复该怎么办”。

$directory = "/path/to/images";

if ($handle = opendir($directory)) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != '.' && $entry != '..') {

            // Check "(1"
            if (preg_match('/\(1/', $entry)) {

                // Rename file
                $old = $directory . '/' . $entry;
                $new = str_replace('(1', '', $old);

                // Check duplicate
                if (file_exists($new)) {
                    $extension = strrpos($new, '.');
                    $new       = substr($new, 0, $extension) . rand() . substr($new, $extension); // Basic rand()
                }

                rename($old, $new);
            }
        }
    }
    closedir($handle);
}
票数 2
EN

Stack Overflow用户

发布于 2018-06-10 04:55:10

如果您只想从图像名称中删除一些子字符串,则无需使用正则表达式即可完成此操作。使用str_replace函数将子串替换为空字符串。举个例子:

$name = "112345(1.jpg";
$substring = "(1";
$result = str_replace($substring, "", $name);
票数 1
EN

Stack Overflow用户

发布于 2018-06-10 04:59:04

您可以使用scandir和preg_grep过滤出需要重命名的文件。

$allfiles = scandir("folder"); // replace with folder with jpg files
$filesToRename = preg_grep("/\(1\.jpg/i", $allfiles);

Foreach($filesToRename as $file){
    Echo $file . " " . Var_export(rename($file, str_replace("(1.", ".", $file));
}

这是未经测试的代码,理论上,如果重命名起作用或不起作用,它应该回显文件名和true/false。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50778267

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档