码迷,mamicode.com
首页 > 其他好文 > 详细

批量去除文件的BOM头

时间:2017-04-24 15:27:11      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:result   sep   class   foreach   ext   false   路径   path   bom   

<?php

class KillBom
{
//定义扩展名
public static $m_ext = [‘txt‘,‘php‘,‘js‘,‘css‘];

/**
* 传入一个任意文件,自动区分定义的扩展名,然后过滤
* @param string $file
* @return boolean
*/
public static function killBomByFile($file)
{
//获取一个文件的扩展名
$ext = pathinfo($file,PATHINFO_EXTENSION);
if (in_array($ext, self::$m_ext) and is_file($file))//允许被替换,而且是个文件(不是目录)
{
$content = file_get_contents($file);//取出文件详情
if (substr($content, 0, 3) == chr(0xEF) . chr(0xBB) . chr(0xBF))//ef.bb.bf检查bom头
{
return file_put_contents($file,substr($content, 3)) > 0;//清除bom并写入文件
}
}
return false;
}

/**
* 遍历获取子目录 及文件夹
* @param string $dir
* @return string[]
*/

public static function getFileListByDir($dir)
{
//打开文件
$dir_handle = opendir($dir);
//存储结果
$result = [];
while ($file = reddir($dir_handle))//不断读取目录
{
if ($file != ‘.‘ and != ‘..‘)//不是本级目录,上级目录
//组装成绝对路径 DIRECTORY_SEPARATOR目录分隔符,windows为\,linux为/
$file = $dir . DIRECTORY_SEPARATOR . $file;
if (is_dir($file))// 是目录的话
{
//递归合并结果
$result = array_merge($result , self::getFileListByDir($file));
}
else
{
$result[] = $file;// 记录结果
}
}
return $result;//返回结果
}


/**
* 清空目录下所有Bom头文件
* @param string $dir
*/
public function killDir($dir)
{
//先找到所有文件
$files = self::getFileListByDir($dir);
foreach ($files as $file)
{
if (!self::killBomByFile($file))//干掉
{
echo $file . ‘-> no bom! <br>‘.chr(13);//结果
}
else
{
echo $file . ‘-> bom is killed! <br>‘.chr(13);//结果
}
}
}
}
//调用
killBom::killDir(‘你的目录‘);

批量去除文件的BOM头

标签:result   sep   class   foreach   ext   false   路径   path   bom   

原文地址:http://www.cnblogs.com/jingxiaoniu/p/6756844.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!