我在服务器上有一个文件夹,里面有很多图像,我想重命名一些图像。包含(1
的镜像示例:
112345(1.jpg to 112345.jpg
。如何在PHP中使用regex执行此操作?我不得不提一下,我对PHP的了解非常有限,它是唯一一种可以有效地编写脚本的语言。
发布于 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);
}
发布于 2018-06-10 04:55:10
如果您只想从图像名称中删除一些子字符串,则无需使用正则表达式即可完成此操作。使用str_replace函数将子串替换为空字符串。举个例子:
$name = "112345(1.jpg";
$substring = "(1";
$result = str_replace($substring, "", $name);
发布于 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。
https://stackoverflow.com/questions/50778267
复制相似问题