Heim  >  Artikel  >  Backend-Entwicklung  >  有关UTF-8 编码中BOM的检测与删除

有关UTF-8 编码中BOM的检测与删除

WBOY
WBOYOriginal
2016-07-25 09:05:271336Durchsuche
  1. Shell: #!/bin/sh: No such file or directory
  2. PHP: Warning: Cannot modify header information – headers already sent
复制代码

在详细讨论UTF-8编码中BOM的检测与删除问题前,不妨先通过一个例子热热身:

  1. shell> curl -s http://phone.jbxue.com/ | head -1 | sed -n l
  2. \357\273\277
  3. //EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\r$
复制代码

如上所示,前三个字节分别是357、273、277,这就是八进制的BOM。

  1. shell> curl -s http://phone.jbxue.com/ | head -1 | hexdump -C
  2. 00000000 ef bb bf 3c 21 44 4f 43 54 59 50 45 20 68 74 6d |...
  3. 00000010 6c 20 50 55 42 4c 49 43 20 22 2d 2f 2f 57 33 43 |l PUBLIC "-//W3C|
  4. 00000020 2f 2f 44 54 44 20 58 48 54 4d 4c 20 31 2e 30 20 |//DTD XHTML 1.0 |
  5. 00000030 54 72 61 6e 73 69 74 69 6f 6e 61 6c 2f 2f 45 4e |Transitional//EN|
  6. 00000040 22 20 22 68 74 74 70 3a 2f 2f 77 77 77 2e 77 33 |" "http://www.w3|
  7. 00000050 2e 6f 72 67 2f 54 52 2f 78 68 74 6d 6c 31 2f 44 |.org/TR/xhtml1/D|
  8. 00000060 54 44 2f 78 68 74 6d 6c 31 2d 74 72 61 6e 73 69 |TD/xhtml1-transi|
  9. 00000070 74 69 6f 6e 61 6c 2e 64 74 64 22 3e 0d 0a |tional.dtd">..|
复制代码

如上所示,前三个字节分别是EF、BB、BF,这就是十六进制的BOM。

注:用到了第三方网站的页面,不能保证例子始终可用。

实际做项目开发时,可能会面对成百上千个文本文件,如果有几个文件混入了BOM,那么很难察觉,如果没有带BOM的UTF-8文本文件例子,可以用vi杜撰几个,相关命令如下: #设置UTF-8编码 :set fileencoding=utf-8 #添加BOM :set bomb #删除BOM :set nobomb #查询BOM :set bomb?

检测UTF-8编码中的BOM

  1. shell> grep -r -I -l $'^\xEF\xBB\xBF' /path
复制代码

删除UTF-8编码中的BOM

  1. shell> grep -r -I -l $'^\xEF\xBB\xBF' /path | xargs sed -i 's/^\xEF\xBB\xBF//;q'
复制代码

推荐:如果使用SVN,可以在pre-commit钩子里加上相关代码用以杜绝BOM。

  1. #!/bin/sh

  2. REPOS="$1"

  3. TXN="$2"
  4. SVNLOOK=/usr/bin/svnlook

  5. FILES=`$SVNLOOK changed -t "$TXN" "$REPOS" | awk '/^[UA]/ {print $2}'`

  6. for FILE in $FILES; do

  7. if $SVNLOOK cat -t "$TXN" "$REPOS" "$FILE" | grep -q $'^\xEF\xBB\xBF'; then
  8. echo "Byte Order Mark be found in $FILE" 1>&2
  9. exit 1
  10. fi
  11. done
复制代码
您可能感兴趣的文章: php实例:检测并清除文件开头的BOM信息 Php批量去除bom头信息的实现代码 php去掉bom头的代码分享 PHP 过滤页面中的BOM数据的简单实例 检测php文件是否有bom头的代码 批量清除php文件中bom的方法 检查并清除php文件中bom的函数 有关 UTF-8 BOM 导致样式错乱的解决方法 BOM与DOM的区别分析


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn