Php: PHP automatically identifies character sets and completes Transcoding

Source: Internet
Author: User

PHP automatically recognizes character sets and completes transcoding because it uses UTF-8 encoding. However, if the other party's 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 [php] 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 judged by $ char =$ string {++ $ I }; if (ord ($ char) & 128) = 128) {// The second byte is judged by $ char =string string {++ $ I }; if (ord ($ char) & 128) = 128) {$ encoding = "UTF-8"; break ;}} if (ord ($ string {$ I }) & 192) = 192) {// The first byte is determined by $ char = $ string {++ $ I}; if (ord ($ char) & 128) = 128) {// The second byte is determined by $ encoding = "GB2312"; break ;}} if (strtoupper ($ encoding) = strtoupper ($ outEncoding )) return $ string; else returniconv ($ encoding, $ outEncoding, $ string );}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.