First, there are two most common types of encoding in mainland China: UTF-8 and GBK/gb2312.
Gb2312 is a simplified Chinese code. GBK/gb2312 is a Chinese encoding, and the two are relatively compatible.
The database stores data, which is generally UTF-8 encoded. In Windows, the default encoding method is gb2312, which leads to inconsistent encoding.
Scenario:
Write data to the database. At this point: we need to change the encoding to utf8 before it can be stored in the database.
In fact, only three simple steps are required: determining the encoding, encoding conversion, and writing data to the database. (Only the conversion between GBK/gb2312 and utf8 encoding is provided, and other non-mainstream similar processes can be used)
I. Encoding
There are many ways to do this:
FunctionIs_utf8 ($ String){
Return Preg_match('% ^ (? :
[\ X09 \ x0a \ x0d \ x20-\ x7e]
| [\ Xc2-\ xdf] [\ X80-\ xbf]
| \ Xe0 [\ xa0-\ xbf] [\ X80-\ xbf]
| [\ Xe1-\ xec \ xee \ XeF] [\ X80-\ xbf] {2}
| \ Xed [\ X80-\ x9f] [\ X80-\ xbf]
| \ Xf0 [\ x90-\ xbf] [\ X80-\ xbf] {2}
| [\ Xf1-\ xf3] [\ X80-\ xbf] {3}
| \ Xf4 [\ X80-\ x8f] [\ X80-\ xbf] {2}
) * $ % Xs ',$ String);
}
This is the range of various encodings:
$ Re['Utf-8'] = "/[\ x01-\ x7f] | [\ xc2-\ xdf] [\ X80-\ xbf] | [\ xe0-\ XeF] [\ X80-\ xbf] {2} | [\ xf0-\ xFF] [\ X80-\ xbf] {3 }/";
$ Re['Gb2312'] = "/[\ x01-\ x7f] | [\ xb0-\ xf7] [\ xa0-\ xfe]/";
$ Re['Gbk'] = "/[\ x01-\ x7f] | [\ x81-\ xfe] [\ X40-\ xfe]/";
$ Re['Big5'] = "/[\ x01-\ x7f] | [\ x81-\ xfe] ([\ X40-\ x7e] | \ xA1-\ xfe]) /";
With this function, you can make a slight modification:
FunctionIs_utf8 ($ String){
Return Preg_match('/[\ X01-\ x7f] | [\ xc2-\ xdf] [\ X80-\ xbf] | [\ xe0-\ XeF] [\ X80-\ xbf] {2} | [\ xf0-\ xFF] [\ X80-\ xbf] {3 }/',$ String);
}
Ii. encoding conversion
There are three methods for encoding conversion: 1. iconv 2. mbstring extension 3. Self-writing Conversion Function
2. Because I have enabled the mbstring extension in PHP, I am using this method.
//UTF-8 to gb2312
$ Str= Mb_convert_encoding ("Yang sen", "gb2312", "UTF-8 ");
//GBK to UTF-8
$ Str= Mb_convert_encoding ($ Str, "UTF-8", "GBK ");
1. iconv Conversion
//UTF-8 to gb2312
// There is a small bug when converting the UTF-8, please add "// ignore" after the second parameter"
Iconv("UTF-8", "gb2312 // ignore ",$ Data)
//Gb2312 to UTF-8
Iconv('Gb2312', 'utf-8 ',$ Str);
3. Self-writing conversion functions I have not written on my own, and I have not written it on my own. It is also obtained through online query. Therefore, you are advised to query the data on the Internet.
4. If the encoding involved in file upload is involved, you can use the above function to directly read and write data.
File_get_contents($ Path);
If(! Is_utf8 ($ Str)){
$ Str= Mb_convert_encoding ($ Str, "UTF-8", "GBK ");
File_put_contents($ Path,$ Str);
}
Then it is written to the database.