[英]get entire folders/files tree and rename
I have a folders/files tree inside admin
folder (windows, localhost). 我在admin
文件夹(Windows,localhost)中有一个文件夹/文件树。
All files are .html
. 所有文件均为.html
。
Each of them (files and folders) is starting with some numbers and middle dash, for example 例如,每个文件(文件和文件夹)都以一些数字和中间的破折号开头
32-somefolder
624-somefile.html
I need to list all of them and remove all prefixes from their names. 我需要列出所有这些名称,并从其名称中删除所有前缀。 So the result should be: 因此结果应为:
somefolder
somefile.html
foreach(glob("admin/*") as $el) {
echo $el . '.' . filetype($el) . '<br>';
}
First problem - only folders are listed: 第一个问题-仅列出文件夹:
admin/32-somefolder.dir
How to get files too, and how to rename ie remove prefixes from all the names? 也如何获取文件,以及如何重命名(即从所有名称中删除前缀)?
You can use the second choice to list files : scandir
, and recursive function : 您可以使用第二个选择列出文件: scandir
和递归函数:
function removePrefixFiles($dir, &$results = array()){
$files = scandir($dir);
foreach ($files as $key => $value){
$path = realpath($dir . DIRECTORY_SEPARATOR . $value);
if (! is_dir($path)) {
// treat the filename
$file = pathinfo($path);
$filename = explode('-', $file['filename']);
if (count($filename) > 0) {
// '-' is found, rename file
rename($path, $file['dirname'] .'/'. $filename[1] .'.'. $file['extension'];
}
$results[] = $path;
} else if ($value != '.' && $value != '..') {
removePrefixFiles($path, $results);
$results[] = $path;
}
}
// no real need to return something here, but can log the files
return $results;
}
$dir = '/admin';
removePrefixFiles($dir);
I have created two folder inside admin/ name as 我在admin /名称中创建了两个文件夹
1-files and 2-abc 1个文件和2个abc
then inside folder 1-files i have two files 然后在文件夹1个文件中,我有两个文件
11-java.html 11 java.html
11-text.html 11 text.html
then inside folder 2-abc i have two files 然后在文件夹2-abc里面我有两个文件
22-php.html 22 php.html
22-sql.html 22 sql.html
<?php
$dir = "admin/";
// Sort in ascending order - this is default
$a = scandir($dir);
echo "<pre>";
if(count($a)>0){
$newArr = array();
for($i=2;$i<count($a);$i++){
$test = array();
$folderArr = array();
$folderName = explode('-',$a[$i]);
$test['folder'] = $folderName[1];
$b = scandir($dir.'/'.$a[$i]);
for($j=2;$j<count($b);$j++){
$fileName = explode('-',$b[$j]);
$folderArr[] = substr($fileName[1], 0, strpos($fileName[1], "."));;
}
$test['files'] = $folderArr;
$newArr[] = $test;
}
}
print_r($newArr);
?>
This will be the output 这将是输出
Array
(
[0] => Array
(
[folder] => files
[files] => Array
(
[0] => java
[1] => text
)
)
[1] => Array
(
[folder] => abc
[files] => Array
(
[0] => php
[1] => sql
)
)
)
Hope this willl hellp you. 希望这会帮助你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.