+ -
当前位置:首页 → 问答吧 → 指定目录内的文本文件字符串批量替换

指定目录内的文本文件字符串批量替换

时间:2007-12-12

来源:互联网

类 dfilelist 列出目录内所有指定类型的文件
引用:
class dfilelist {
var $filesarray = array();

function fileext($filename) {
return strtolower(trim(substr(strrchr($filename, '.'), 1, 10)));
}

function dscandir($dir, $fileext = '') {
$dirfiles = scandir($dir);
foreach ($dirfiles as $file) {
if ($file != "." && $file != "..") {
$newfile = "$dir/$file";
if (is_dir($newfile)) {
$this->dscandir($newfile, $fileext);
}
else {
if ($fileext) {
if (in_array($this->fileext($file), explode('|', $fileext))) {
$this->filesarray[] = $newfile;
}
}
else {
$this->filesarray[] = $newfile;
}
}
}
}
}

function filelist($dir, $fileext = '') {
$fileext = strtolower($fileext);
if (is_dir($dir)) {
$this->dscandir($dir, $fileext);
}
else {
return "$dir is not a dir!";
}
return $this->filesarray;
}
}
$filelist = new dfilelist;
$file = $filelist->filelist($dir, 'php|html'); //多个 $fileext 用 | 隔开
函数 dstrreplace 执行字符串替换 如果要求较高 可在函数中使用 preg_replace 函数
$file 文件名;  $search 查找的字串;  $replace 替换的字串;  $trans 为1时不区分大小写
引用:
function dstrreplace($file, $search, $replace = '', $trans = 0) {
if (is_readable($file) && is_writable($file)) {
$datas = file_get_contents($file);
if ($trans) {
$datas = str_ireplace($search, $replace, $datas);
} else {
$datas = str_replace($search, $replace, $datas);
}
if($fp = @fopen($file, 'w')) {
flock($fp, LOCK_EX);
fwrite($fp, $datas);
}
@fclose($fp);
//chmod($file, 0777);
}
}
读取数组$file内的文件,执行替换
foreach ($file as $f) {
dstrreplace($f, $search, $replace);
}

[ 本帖最后由 cuans 于 2007-12-11 20:35 编辑 ]

作者: cuans   发布时间: 2007-12-11

有想法

作者: edwardhey   发布时间: 2007-12-11