在php中重命名目录的所有子目录
我的目录结构如下:在php中重命名目录的所有子目录,php,Php,我的目录结构如下: . ├── uploads | ├── 1 | | ├── example.jpeg | | └── example.jpeg | ├── 2 | | └── example.jpeg | ├── 3 | | ├── example.jpeg | | ├── example.jpeg | | └── example.jpeg 我希望重命名FireFactory中上载的所有目录(在我的示例中,这些目录称为1、2和3)
.
├── uploads
| ├── 1
| | ├── example.jpeg
| | └── example.jpeg
| ├── 2
| | └── example.jpeg
| ├── 3
| | ├── example.jpeg
| | ├── example.jpeg
| | └── example.jpeg
我希望重命名FireFactory中上载的所有目录(在我的示例中,这些目录称为1
、2
和3
)。我想根据这些目录的当前名称重命名它们。例如,我希望1
变成1asd
,2
变成2asd
,3
变成3asd
。我寻找过类似的问题,发现(虽然问题看起来很相似,但实际上是关于其他事情的)和(关于重命名文件的)。
我试过:
if ($handle = opendir('../path/to/uploads')) {
while (false !== ($fileName = readdir($handle))) {
$newName = $fileName.'asd';
rename($fileName, $newName);
}
closedir($handle);
}
这不起作用,因为所有$filename
始终是
。我猜是因为它是关于目录而不是文件的。如何将目标指向目录
旁注1:我希望重命名的目录包含我不希望丢失/删除的文件。在我的示例中,它们都被称为example.jpeg
旁注2:我的
上传
目录路径正确,我测试了这个 您要检查以确保它是一个目录,并检查它不是当前目录
或父目录。
目录:
if(is_dir($fileName) && $fileName!= "." && $fileName!= "..") {
$newName = $fileName.'asd';
rename($fileName, $newName);
}
另外,正如所述,
$newName=$fileName.asd')中存在语法错误代码>,注意右括号。使用和
请确保从正确的目录运行此操作,或相应地更改路径
如果PHP
脚本位于uploads
foreach (glob("uploads/[1|2|3]",GLOB_ONLYDIR) as $filename) {
rename($filename, $filename."asd");
}
如果有多个目录,则上述内容将稍微更改为以下内容:
$directories = array_merge_recursive(glob("uploads/[0-9]*[0-9]",GLOB_ONLYDIR),glob("uploads/[0-9]",GLOB_ONLYDIR));
foreach ($directories as $directory) {
rename($directory, $directory."asd");
}
glob(“uploads/[0-9]*[0-9]”,glob_ONLYDIR)
匹配从数字开始到1结束的任何内容
glob(“uploads/[0-9]”,glob\u ONLYDIR)
匹配任何名称为一位数字的目录。经过一些尝试和错误,我设法找到了一个解决方案:
$dir = '../path/to/uploads/';
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($filename = readdir($dh)) !== false) {
if($filename!= "." && $filename!= "..") {
rename($dir.$filename, $dir.$filename."asd");
}
}
closedir($dh);
}
}
$newName=$fileName.asd')中存在语法错误代码>,注意右括号?这只是打字错误吗?@mcserep,谢谢。虽然不是这样,但这只是一个打字错误。不知怎的,这不起作用。我试图var\u dump
却一无所获。当我使用is_dir($filename
I)执行var_dump
时,我确实可以看到我的目录。但是当我运行代码时,我会看到一个错误,如:Warning:rename(135asd):系统找不到指定的文件。(代码:2)
当我有数百个不同编号的子目录时,我该怎么做?@DirkJ.Faber子目录编号是否有模式?您可以执行上面示例中的正则表达式。所有子目录都由编号组成。介于1和99999之间,但不是1、2、3等。。。