PHP批量去除Bom头的方法

检查的代码:

php 复制代码
<?php

$dir = __DIR__;
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));

foreach ($files as $file) {
    if ($file->isFile() && pathinfo($file, PATHINFO_EXTENSION) === 'php') {
        $content = file_get_contents($file->getPathname());
        if (substr($content, 0, 3) === "\xEF\xBB\xBF") {
            echo "BOM found in: " . $file->getPathname() . "\n";
        } else {
            echo "No BOM in: " . $file->getPathname() . "\n";
        }
    }
}

批量去除Bom头的代码:

php 复制代码
<?php



$dir = __DIR__; // 当前目录
$files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir));

foreach ($files as $file) {
    if ($file->isFile() && pathinfo($file, PATHINFO_EXTENSION) === 'php') {
        echo "Checking: " . $file->getPathname() . "\n"; // 打印正在处理的文件
        $content = file_get_contents($file->getPathname());
        if (substr($content, 0, 3) === "\xEF\xBB\xBF") {
            $content = substr($content, 3);
            file_put_contents($file->getPathname(), $content);
            echo "Removed BOM from: " . $file->getPathname() . "\n";
        }
    }
}

但是最后的方法是:

bash 复制代码
xxd index3.php | head -n 1

发现没有bom头,用PHPStorm右下角的 CR utf-8 改成 CRLF utf-8 就好了。

为什么呢?

CRLF(\r\n):Windows 默认的换行符,两个字符 0x0D 0x0A。

CR(\r):旧版 macOS 使用的换行符,单个 0x0D。

LF(\n):Linux/macOS 默认的换行符,单个 0x0A。

换行格式 符号 ASCII 码 操作系统
LF(换行 Line Feed) \n 0x0A Linux、macOS(新版本)
CR(回车 Carriage Return) \r 0x0D 旧版 macOS(Mac OS 9 及更早)
CRLF(回车+换行) \r\n 0x0D 0x0A Windows
格式 适用系统 影响
CRLF UTF-8 Windows Windows 兼容,Linux 可能会有 ^M 问题
CR UTF-8 旧版 macOS Linux 解析可能出错,现代系统不推荐
LF UTF-8 Linux/macOS 适用于 PHP / Shell / Linux 服务器
相关推荐
雪度娃娃11 小时前
Asio异步读写——连接的安全回收问题
开发语言·c++·安全·php
陌路2014 小时前
详解C++ 高性能网络库 muduo 的精简日志模块
开发语言·c++·php
我是伪码农15 小时前
小程序100-125
开发语言·小程序·php
c++逐梦人15 小时前
epoll ET服务器(Reactor模式)
运维·服务器·php
牛奔15 小时前
codebuddy 桌面版 如何配置自己的模型
运维·服务器·开发语言·php
跨境数据猎手16 小时前
代购系统技术选型全复盘:Laravel / Go / 自研 / SaaS 怎么选
爬虫·php·laravel
祁白_17 小时前
PHP无参读取文件与RCE总结
安全·php·writeup·总结·rce
XiYang-DING17 小时前
【Java EE】IPv6
java·java-ee·php
likerhood17 小时前
Java 异常处理:从 try-catch-finally 到项目最佳实践
java·开发语言·php
曦夜日长18 小时前
Linux系统篇,开发工具(六):文件的编译配置、调试的理解、cgdb和gdb的操作使用
java·linux·php