//author: selfimpr
//blog: http://blog.csdn.net/lgg201
//mail: [email protected]
//EF BB BF这三个字节称为bom头
function hasbom(&$content) {
$firstline = $content[0];
return ord(substr($firstline, 0, 1)) === 0xEF
and ord(substr($firstline, 1, 1)) === 0xBB 
and ord(substr($firstline, 2, 1)) === 0xBF;
}
function unsetbom(&$content) {
hasbom($content) and ($content[0] = substr($content[0], 3)); 
}
function write($filename, &$content) {
$file = fopen($filename, 'w');
fwrite($file, implode($content, ''));
fclose($file);
}
function filenames($path) {
$directory = opendir($path);
while (false != ($filename = readdir($directory))) strpos($filename, '.') !== 0 and $filenames[] = $filename;
closedir($directory);
return $filenames;
}
function process($path) {
$parent = opendir($path);
while (false != ($filename = readdir($parent))) {
echo $filename."\n";
if(strpos($filename, '.') === 0) continue;
if(is_dir($path.'/'.$filename)) {
process($path.'/'.$filename);
} else {
$content = file($path.'/'.$filename);
unsetbom($content);
write($path.'/'.$filename, $content);
}
}
closedir($parent);
}
process('/home/selfimpr/t');

解决方案 »

  1.   

    那个filenames是没用的 ....汗...不小心贴进来了
      

  2.   

    给你优化一下/*** 将 process 改写成通用的可带回调函数的目录遍历函数 ***/
    function process($path, $func='') {
        $parent = opendir($path);
        while (false != ($filename = readdir($parent))) {
            echo $filename."\n";
            if(strpos($filename, '.') === 0) continue;
            $filename = $path.'/'.$filename;
            if(is_dir($filename)) {
                process($filename, $func);
            } else {
                if($func) $func($filename);
            }
        }
        closedir($parent);
    }/*** 删除 BOM 头的函数 ***/
    function unsetbom($filename) {
      $content = file_get_contents($filename);
      $s = substr($content, 0, 3);
      if(array_pop(unpack('H*',$s)) == 'efbbbf') {
        file_put_contents($filename, substr($content, 3));
      }
    }/*** 调用示例 ***/
    process('/home/selfimpr/t', 'unsetbom');