Let's not say much about it. the function is used to check and transcode strings. For more information, see UTF-8 encoding. However, if the other blog uses gb2312 encoding, garbled characters will appear after the POST (unless the encoding is converted before the POST ). It is necessary to perform an encoding check and conversion on your own without ensuring that the other party must use UTF-8 encoding.
I wrote a function to complete this operation. The principle is very simple. because gb2312/gbk is a two-byte Chinese character, these two bytes have a value range, while UTF-8 contains three Chinese characters, each byte also has a value range. English, regardless of the encoding, is less than 128, only occupies one byte (excluding the full width ).
For file-based encoding checks, you can also directly check the BOM information of UTF-8. For more information, see the encoding conversion function of the TP toolbox, I wrote a detailed comment in the AppCodingSwitch class.
Let's not say much about it. the function is used to check and transcode strings. File Check and transcoding
The code is as follows:
Function safeEncoding ($ string, $ outEncoding = 'utf-8 '){
$ Encoding = "UTF-8 ";
For ($ I = 0; $ I <strlen ($ string); $ I ++ ){
If (ord ($ string {$ I}) <128)
Continue;
If (ord ($ string {$ I}) & 224) = 224 ){
// The first byte is determined
$ Char = $ string {++ $ I };
If (ord ($ char) & 128) = 128 ){
// The second byte is passed
$ Char = $ string {++ $ I };
If (ord ($ char) & 128) = 128 ){
$ Encoding = "UTF-8 ";
Break;
}
}
}
If (ord ($ string {$ I}) & 192) = 192 ){
// The first byte is determined
$ Char = $ string {++ $ I };
If (ord ($ char) & 128) = 128 ){
// The second byte is passed
$ Encoding = "GB2312 ";
Break;
}
}
}
If (strtoupper ($ encoding) = strtoupper ($ outEncoding ))
Return $ string;
Else
Returniconv ($ encoding, $ outEncoding, $ string );
}