programing tip

파일 시작 부분에서 를 어떻게 제거합니까?

itbloger 2020. 6. 22. 08:05
반응형

파일 시작 부분에서 를 어떻게 제거합니까?


gedit를 사용하여 열면 괜찮아 보이는 CSS 파일이 있지만 PHP에서 읽을 때 (모든 CSS 파일을 하나로 병합하기 위해)이 CSS에는 다음 문자가 앞에 붙습니다.

PHP는 모든 공백을 제거하므로 코드 중간에 임의의 가 전체를 엉망으로 만듭니다. 언급했듯이 gedit에서 파일을 열면 실제로 이러한 문자를 볼 수 없으므로 쉽게 제거 할 수 없습니다.

나는 문제를 봤다. 파일 인코딩에는 분명히 문제가있다. 이것은 다양한 텍스트 편집기로 ftp 및 rsync 를 통해 파일을 다른 Linux / Windows 서버로 옮기는 것처럼 말이된다 . 문자 인코딩에 대해서는 잘 모르므로 도움을 주시면 감사하겠습니다.

도움이된다면 파일이 UTF-8 형식으로 저장되고 gedit에서 ISO-8859-15 형식으로 저장할 수 없습니다 (문서에 지정된 문자 인코딩을 사용하여 인코딩 할 수없는 하나 이상의 문자가 포함되어 있음). Windows 및 Linux 줄 끝으로 저장하려고 시도했지만 도움이되지 않았습니다.


당신을위한 세 단어 :

바이트 주문 마크 (BOM)

이것이 ISO-8859-1의 UTF-8 BOM 표현입니다. BOM을 사용하지 않도록 편집기에 지시하거나 다른 편집기를 사용하여 BOM을 제거해야합니다.

BOM 제거를 자동화하기 위해이 질문에awk 표시된대로 사용할 수 있습니다 .

또 다른 대답에서 알 수 있듯이 PHP가 실제로 BOM을 올바르게 해석하는 것이 가장 좋습니다 mb_internal_encoding(). 다음과 같이 사용할 수 있습니다 .

 <?php
   //Storing the previous encoding in case you have some other piece 
   //of code sensitive to encoding and counting on the default value.      
   $previous_encoding = mb_internal_encoding();

   //Set the encoding to UTF-8, so when reading files it ignores the BOM       
   mb_internal_encoding('UTF-8');

   //Process the CSS files...

   //Finally, return to the previous encoding
   mb_internal_encoding($previous_encoding);

   //Rest of the code...
  ?>

PHP 에서는 다음을 수행하여 해당 문자를 포함하여 모든 비 문자를 제거 할 수 있습니다.

$response = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $response);

메모장 ++ 에서 파일을 엽니 다 . 로부터 인코딩 메뉴에서 BOM없이 UTF-8로 변환을 , 파일 저장이 새로운 파일로 이전 파일을 교체합니다. 그리고 그것은 효과가 있습니다.


쉘 액세스 권한이있는 사용자의 경우 public_html 디렉토리에 BOM이 설정된 모든 파일을 찾기위한 작은 명령이 있습니다. 서버에서 올바른 경로로 변경하십시오.

암호:

grep -rl $'\xEF\xBB\xBF' /home/username/public_html

vi 편집기에 익숙한 경우 vi 에서 파일을여십시오.

vi /path-to-file-name/file.php

다음 명령을 입력하여 BOM을 제거하십시오.

set nobomb

파일을 저장하십시오.

wq

BOM은 일련의 문자 (UTF-8의 경우 $ EF $ BB $ BF)이므로 스크립트를 사용하여 제거하거나 편집기가 추가되지 않도록 구성하십시오.

에서 UTF-8에서 BOM을 제거 :

#!/usr/bin/perl
@file=<>;
$file[0] =~ s/^\xEF\xBB\xBF//;
print(@file);

PHP로 쉽게 번역된다고 확신합니다.


나를 위해, 이것은 효과가 있었다 :

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

이 메타를 제거하면 가 다시 나타납니다. 이것이 누군가를 돕기를 바랍니다 ...


PHP를 모르므로 이것이 가능한지 모르겠지만 가장 좋은 해결책은 파일을 다른 인코딩 대신 UTF-8로 읽는 것입니다. BOM은 실제로 ZERO WIDTH NO BREAK SPACE입니다. 이것은 공백이므로 파일을 올바른 인코딩 (UTF-8)으로 읽으면 BOM이 공백으로 해석되어 결과 CSS 파일에서 무시됩니다.

또한 올바른 인코딩으로 파일을 읽을 때의 또 다른 장점은 문자가 잘못 해석 될 염려가 없다는 것입니다. 편집자가 저장하려는 코드 페이지가 필요한 모든 문자를 수행하지는 않는다고 알려줍니다. PHP가 잘못된 인코딩으로 파일을 읽는 경우 BOM 이외의 다른 문자가 자동으로 잘못 해석 될 가능성이 큽니다. 모든 곳에서 UTF-8을 사용하면 이러한 문제가 사라집니다.


당신이 사용할 수있는

vim -e -c 'argdo set fileencoding=utf-8|set encoding=utf-8| set nobomb| wq'

awk로 바꾸는 것이 효과가있는 것처럼 보이지만 제자리에 없습니다.


grep -rl $ '\ xEF \ xBB \ xBF'* | xargs vim -e -c 'argdo set fileencoding = utf-8 | 세트 인코딩 = utf-8 | 폭탄을 설정 | wq '


일부 PHP 파일 ( )에 BOM과 동일한 문제가있었습니다.

If you use PhpStorm you can set at hotkey to remove it in Settings -> IDE Settings -> Keymap -> Main Menu - > File -> Remove BOM.


In Notepad++, choose the "Encoding" menu, then "Encode in UTF-8 without BOM". Then save.

See Stack Overflow question How to make Notepad to save text in UTF-8 without BOM?.


Open the PHP file under question, in Notepad++.

Click on Encoding at the top and change from "Encoding in UTF-8 without BOM" to just "Encoding in UTF-8". Save and overwrite the file on your server.


Same problem, different solution.

One line in the PHP file was printing out XML headers (which use the same begin/end tags as PHP). Looks like the code within these tags set the encoding, and was executed within PHP which resulted in the strange characters. Either way here's the solution:

# Original
$xml_string = "&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;";

# fixed
$xml_string = "<" . "?xml version=\"1.0\" encoding=\"UTF-8\"?" . ">";

If you need to be able to remove the BOM from UTF-8 encoded files, you first need to get hold of an editor that is aware of them.

I personally use E Text Editor.

In the bottom right, there are options for character encoding, including the BOM tag. Load your file, deselect Byte Order Marker if it is selected, resave, and it should be done.

Alt text http://oth4.com/encoding.png

E is not free, but there is a free trial, and it is an excellent editor (limited TextMate compatibility).


You can open it by PhpStorm and right-click on your file and click on Remove BOM...


Here is another good solution for the problem with BOM. These are two VBScript (.vbs) scripts.

One for finding the BOM in a file and one for KILLING the damned BOM in the file. It works pretty fine and is easy to use.

Just create a .vbs file, and paste the following code in it.

You can use the VBScript script simply by dragging and dropping the suspicious file onto the .vbs file. It will tell you if there is a BOM or not.

' Heiko Jendreck - personal helpdesk & webdesign
' http://www.phw-jendreck.de
' 2010.05.10 Vers 1.0
'
' find_BOM.vbs
' ====================
' Kleines Hilfsmittel, welches das BOM finden soll
'
 Const UTF8_BOM = ""
 Const UTF16BE_BOM = "þÿ"
 Const UTF16LE_BOM = "ÿþ"
 Const ForReading = 1
 Const ForWriting = 2
 Dim fso
 Set fso = WScript.CreateObject("Scripting.FileSystemObject")
 Dim f
 f = WScript.Arguments.Item(0)
 Dim t
 t = fso.OpenTextFile(f, ForReading).ReadAll
 If Left(t, 3) = UTF8_BOM Then
     MsgBox "UTF-8-BOM detected!"
 ElseIf Left(t, 2) = UTF16BE_BOM Then
     MsgBox "UTF-16-BOM (Big Endian) detected!"
 ElseIf Left(t, 2) = UTF16LE_BOM Then
     MsgBox "UTF-16-BOM (Little Endian) detected!"
 Else
     MsgBox "No BOM detected!"
 End If

If it tells you there is BOM, go and create the second .vbs file with the following code and drag the suspicios file onto the .vbs file.

' Heiko Jendreck - personal helpdesk & webdesign
' http://www.phw-jendreck.de
' 2010.05.10 Vers 1.0
'
' kill_BOM.vbs
' ====================
' Kleines Hilfmittel, welches das gefundene BOM löschen soll
'
Const UTF8_BOM = ""
Const ForReading = 1
Const ForWriting = 2
Dim fso
Set fso = WScript.CreateObject("Scripting.FileSystemObject")
Dim f
f = WScript.Arguments.Item(0)
Dim t
t = fso.OpenTextFile(f, ForReading).ReadAll
If Left(t, 3) = UTF8_BOM Then
    fso.OpenTextFile(f, ForWriting).Write (Mid(t, 4))
    MsgBox "BOM gelöscht!"
Else
    MsgBox "Kein UTF-8-BOM vorhanden!"
End If

The code is from Heiko Jendreck.


In PHPStorm, for multiple files and BOM not necessarily at the beginning of the file, you can search \x{FEFF} (Regular Expression) and replace with nothing.


Same problem, but it only affected one file so I just created a blank file, copy/pasted the code from the original file to the new file, and then replaced the original file. Not fancy but it worked.


Use Total Commander to search for all BOMed files:

Elegant way to search for UTF-8 files with BOM?

  • Open these files in some proper editor (that recognizes BOM) like Eclipse.

  • Change the file's encoding to ISO (right click, properties).

  • Cut  from the beginning of the file, save

  • Change the file's encoding back to UTF-8

...and do not even think about using n...d again!


I had the same problem. The problem was because one of my php files was in utf-8 (the most important, the configuaration file which is included in all php files).

In my case, I had 2 different solutions which worked for me :

First, I changed the Apache Configuration by using AddDefaultCharsetDirective in configuration files (or in .htaccess). This solution forces Apache to use the correct encodage.

AddDefaultCharset ISO-8859-1

The second solution was to change the bad encoding of the php file.


  1. Copy the text of your filename.css file.
  2. Close your css file.
  3. Rename it filename2.css to avoid a filename clash.
  4. In MS Notepad or Wordpad, create a new file.
  5. Paste the text into it.
  6. Save it as filename.css, selecting UTF-8 from the encoding options.
  7. Upload filename.css.

Check on your index.php, find "... charset=iso-8859-1" and replace it with "... charset=utf-8".

Maybe it'll work.

참고URL : https://stackoverflow.com/questions/3255993/how-do-i-remove-%c3%af-from-the-beginning-of-a-file

반응형