PHP中文俱乐部's Archiver

zyfpb 发表于 2009-6-2 10:41

怎样用PHP批量替换目录中UFT8编码文件中的中文字符

我想用PHP批量替换一个目录下面编码为UTF8的所有HTML文件中的一对中文字符,替换不了,只能替换非中文字符。要怎么样操作才能正确替换中文字符呢?
看下面代码中:
如果:
      $search="network";
      $replace="website";
是可以执行批量替换的
但是:
$search="网络";
$replace="网页";
就不能完成替换操作了.
求高人给一个解决方案,谢谢了[code]
<?php
//类 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;
}
}
//函数 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);
}
}
$filelist = new dfilelist;
$dir="gaweb";
$file = $filelist->filelist($dir, 'php|html'); //多个 $fileext 用 | 隔开
//print_r($file);
//exit;
$search="network";
$replace="website";
foreach ($file as $f) {
dstrreplace($f, $search, $replace);
}
?>
[/code]

页: [1]

Powered by Discuz! Archiver 6.1.0  © 2001-2007 Comsenz Inc.