• 批量去BOM头 遍历目录及子文件,文件夹 PHP源码


     1 <?php
     2 class KillBom
     3 {
     4     public static $m_Ext = ['txt', 'php', 'js', 'css'];//检查的扩展名 
     5     /**
     6      * 传入一个任意文件 ,自动区分定义的扩展名,然后过滤bom
     7      * @param string $file
     8      * @return boolean
     9      */
    10     public static  function killBomByFile($file)
    11     {
    12         $ext = pathinfo($file,PATHINFO_EXTENSION);//获取一个文件 的扩展名 
    13         if (in_array($ext, self::$m_Ext) and  is_file($file))//允许被替换,而且是个文件 (不是目录 )
    14         {
    15             $content = file_get_contents($file);//取出文件 详情
    16          
    17             if (substr($content, 0, 3) == chr(0xEF) . chr(0xBB) . chr(0xBF))//EFBBBF 检查bom
    18             {
    19                 return file_put_contents($file, substr($content, 3)) > 0;//清除bom并写入文件 
    20             }
    21         }
    22         return false;
    23     }
    24     /**
    25      * 遍历获取子目录 及文件夹
    26      * @param string $dir
    27      * @return string[]
    28      */
    29     public static function  getFileListByDir($dir)
    30     {
    31         $dir_handle = opendir($dir);//打开文件 
    32         $result = [];//存结果
    33         while ($file = readdir($dir_handle))//不断读取目录 
    34         {
    35             if ($file != '.' and $file != '..')//不是本,上级目录 
    36             {
    37                 $file = $dir . DIRECTORY_SEPARATOR . $file;//组装成文件的绝对路径
    38                 if (is_dir($file))//是目录 的话
    39                 {
    40                     $result = array_merge($result ,  self::getFileListByDir($file));//递归并合并结果
    41                 } else {
    42                     $result[] = $file;//记录结果
    43                 }
    44             }
    45         }
    46         return $result;//返回结果
    47     }
    48     /**
    49      * 清空目录 下所有的bom头文件
    50      * @param string $dir
    51      */
    52     public static function killDir($dir)
    53     {
    54         $files = self::getFileListByDir($dir);//先找到所有文件 
    55         foreach ($files as $file)//遍历
    56         {
    57             if (!self::killBomByFile($file))//干掉
    58             {
    59                 echo $file .' -> no bom! <br>'.chr(13);//结果
    60             } else {
    61                 echo $file . ' -> bom is killed! <br>'.chr(13);//结果
    62             }
    63         }
    64          
    65     }
    66 }
    67 //把下面这行替换成自己的目录
    68 KillBom::killDir('您的目录');
  • 相关阅读:
    Bean
    DI
    require import export
    JSON转js
    vue路由相关
    JS引号区别
    Go语言系列之标准库strconv
    Go语言系列之标准库flag
    Go语言系列之并发编程
    Go语言系列之自定义实现日志库
  • 原文地址:https://www.cnblogs.com/yx520zhao/p/6688812.html
Copyright © 2020-2023  润新知