我在/ public_html /目录中有这些文件:
0832.php
1481.php
2853.php
3471.php
index.php
我希望将所有 XXXX.php (总是以4位数格式)移动到目录/ tmp /,index.php除外。如何用reg-ex和loop做到这一点?
或者,如何将所有文件(包括index.php)首先移动到/ tmp /然后再将index.php放回/ public_html /,您认为哪个文件占用的CPU较少?
最后,我发现本教程使用PHP移动文件:http://www.kavoir.com/2009/04/php-copying-renaming-and-moving-a-file.html
但是如何在目录中移动所有文件?
答案 0 :(得分:2)
您可以将FilesystemIterator
与RegexIterator
$source = "FULL PATH TO public_html";
$destination = "FULL PATH TO public_html/tmp";
$di = new FilesystemIterator($source, FilesystemIterator::SKIP_DOTS);
$regex = new RegexIterator($di, '/\d{4}\.php$/i');
foreach ( $regex as $file ) {
rename($file, $destination . DIRECTORY_SEPARATOR . $file->getFileName());
}
答案 1 :(得分:1)
Regexes实际上是矫枉过正的,因为我们只需要进行一些简单的字符串匹配:
$dir = 'the_directory/';
$handle = opendir($dir) or die("Problem opening the directory");
while ($filename = readdir($handle) !== false)
{
//if ($filename != 'index.php' && substr($filename, -3) == '.php')
// I originally thought you only wanted to move php files, but upon
// rereading I think it's not what you really want
// If you don't want to move non-php files, use the line above,
// otherwise the line below
if ($filename != 'index.php')
{
rename($dir . $filename, '/tmp/' . $filename);
}
}
然后问题:
或者,如何将所有文件(包括index.php)首先移动到/ tmp /然后再将index.php放回/ public_html /,你觉得哪个CPU消耗较少?
可以这样做,而且你的CPU可能会稍微容易一些。但是,有几个原因导致这无关紧要。首先,你已经通过PHP完成了这个非常低效的方式,所以除非你愿意在PHP之外做这件事,否则你不应该真正关注这对你的CPU造成的压力。其次,这会导致更多磁盘访问(特别是如果源和目标目录不在同一磁盘或分区上),并且磁盘访问速度远远低于CPU。
答案 2 :(得分:1)
事实上 - 我去了readdir manual页面,第一个读的评论是:
loop through folders and sub folders with option to remove specific files.
<?php
function listFolderFiles($dir,$exclude){
$ffs = scandir($dir);
echo '<ul class="ulli">';
foreach($ffs as $ff){
if(is_array($exclude) and !in_array($ff,$exclude)){
if($ff != '.' && $ff != '..'){
if(!is_dir($dir.'/'.$ff)){
echo '<li><a href="edit_page.php?path='.ltrim($dir.'/'.$ff,'./').'">'.$ff.'</a>';
} else {
echo '<li>'.$ff;
}
if(is_dir($dir.'/'.$ff)) listFolderFiles($dir.'/'.$ff,$exclude);
echo '</li>';
}
}
}
echo '</ul>';
}
listFolderFiles('.',array('index.php','edit_page.php'));
?>
答案 3 :(得分:1)
最好的方法是直接通过文件系统来完成,但是如果你必须用PHP做这件事,这样的事情应该做你想要的 - 你必须改变路径以便它们是正确的,显然。请注意,这假设public_html目录中可能有其他文件,因此它只获取包含4个数字的文件名。
$d = dir("public_html");
while (false !== ($entry = $d->read())) {
if($entry == '.' || $entry == '..') continue;
if(preg_match("@^\d{4}$@", basename($entry, ".php")) {
// move the file
rename("public_html/".$entry, "/tmp/".$entry));
}
}
$d->close();