在Php中使用正则表达式批量重命名

时间:2018-06-09 20:29:21

标签: php regex

我在服务器中有一个包含大量图像的文件夹,我想重命名一些图像。包含(1示例的图片:
112345(1.jpg to 112345.jpg。如何在PHP中使用正则表达式执行此操作?我必须提到我对PHP的了解非常有限,它是唯一可以有效执行脚本编写的语言。

4 个答案:

答案 0 :(得分:2)

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);
}

答案 1 :(得分:1)

如果您只想从图像名称中删除一些子字符串,则可以在没有正则表达式的情况下执行此操作。使用str_replace函数将子字符串替换为空字符串。 例如:

import numpy as np
import matplotlib.pyplot as plt

# input signal
x = np.arange(1,100,1)
y = 0.3 * np.sin(t) + 0.7 * np.cos(2 * t) - 0.5 * np.sin(1.2 * t)
threshold = 0.95

# max
maxi = np.where(np.where([(y - np.roll(y,1) > 0) & (y - np.roll(y,-1) > 0)],y, 0)> threshold, y,np.nan)
# min
mini = np.where(np.where([(y - np.roll(y,1) < 0) & (y - np.roll(y,-1) < 0)],y, 0)< -threshold, y,np.nan)

答案 2 :(得分:1)

您可以使用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。

答案 3 :(得分:0)

如果需要断言子字符串的位置,只需使用正则表达式,例如:如果你有像Copy (1)(1.23(1.jpg这样的文件名,那么简单的字符串替换就会出错。

$re = '/^(.+)\(1(\.[^\\\\]+)$/';
$subst = '$1$2';
$directory = '/my/root/folder';
if ($handle = opendir($directory )) { 
    while (false !== ($fileName = readdir($handle))) {     
        $newName = preg_replace($re, $subst, $fileName);
        rename($directory . $fileName, $directory . $newName);
    }
    closedir($handle);
}

使用的正则表达式搜索文件扩展名之前和之后的部分,将这些部分放入捕获组,然后在preg_replace中再次将它们粘合在一起,而不是(1

相关问题