读取目录文件,并操作目录文件中数据

1 读取目录文件,并获取列表
function read_dir($dir)
{ $files = []; $dir_list = scandir($dir); foreach ($dir_list as $file) {
if ($file != '..' && $file != '.') {
$file = iconv("gbk", "UTF-8", $file); // 用于获取中文目录
if (is_dir($dir . '/' . $file)) { $files[] = read_dir($dir . '/' . $file);
} else { closedir($handle); } return $files;}
$files[] = $file; } } } return $files;}
 
2 读取指定目录,并操作修改目录文件
$dir = "E:desktopspecial"; $files = read_dir($dir);
foreach ($files as $file) { $path = iconv("UTF-8", "gbk", $dir . '\'.$file);
$newpath = iconv("UTF-8", "gbk", $dir.'\'.'url_'.$file);
if (file_exists($path)) { $fp = fopen($path, "r");
$tmp = []; while (!feof($fp)) { $line = fgets($fp); if($line){ if(preg_match('/.html$/',$line)){ if(strpos($line,'wap')!==false){ $line = str_replace('/home/www/special/html/','http://m.mingshiedu.com/special/',$line);
$line = str_replace('wap/','',$line); }else{ $line = str_replace('/home/www/special/html/','http://www.mingshiedu.com/special/',$line);
$line = str_replace('web/','',$line); }
file_put_contents($newpath, $line, FILE_APPEND); } } }
fclose($fp); }}
echo '处理完成';
 
3 队列方式遍历目录
// 采用递归的方式遍历目录【适合多文件】
function read_dir_queue($dir)
{ $files = [];
$queue = [$dir];
while ($data = each($queue)) {
$path = $data['value'];
if (is_dir($path) && $handle = opendir($path)) {
while ($file = iconv("gbk", 'utf-8', readdir($handle))) { if ($file == '.' || $file == '..') continue;
$real_path = $files[] = $path . '\' . $file;
if (is_dir($real_path)) $queue[] = $real_path; } }

原文地址:https://www.cnblogs.com/sien6/p/13779745.html