[英]Bulk renaming using regex in Php
我的服務器上有一個包含大量圖像的文件夾,我想重命名一些圖像。 包含(1
示例:
112345(1.jpg to 112345.jpg
。如何在PHP中使用正則表達式來做到這一點呢?我不得不提到,我對PHP的了解非常有限,並且它是唯一可以有效執行腳本編寫的語言。
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);
}
如果只想從圖像名稱中刪除一些子字符串,則可以不使用正則表達式。 使用str_replace函數將子字符串替換為空字符串。 例如:
$name = "112345(1.jpg";
$substring = "(1";
$result = str_replace($substring, "", $name);
您可以使用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。
僅在需要聲明子字符串的位置時才使用正則表達式,例如,如果您具有諸如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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.