GBK 和 UTF-8 编码的转换是一个非常恶心的事情,比如像 PHP 中的 json_encode 本身根本不支持 GBK 形式的编码。有两个库函数能够支持编码的转换,通常能够想到的
复制代码 代码如下:
iconv('GBK', 'UTF-8//IGNORE', '脚本之家'); // 将字符串由 GBK 编码转换为 UTF-8 编码
但 iconv 只能解决编码预先知道的情况,如果字符串编码未知,则需要先探测其编码,这时可能会用到 mb_string 扩展库:
复制代码 代码如下:
mb_detect_encoding('脚本之家');
可是 mb_detect_encoding 存在一个硬伤,经常出现判断不准确的情况。或许这样就可以解决:
复制代码 代码如下:
// 使用 iconv 转换并判断是否等值,效率不高
function is_utf8 ($str) {
if ($str === iconv('UTF-8', 'UTF-8//IGNORE', $str)) {
return 'UTF-8';
}
}
// 多种编码的情况
function detect_encoding ($str) {
foreach (array('GBK', 'UTF-8') as $v) {
if ($str === iconv($v, $v . '//IGNORE', $str)) {
return $v;
}
}
}
通过以上方式得到字符串编码信息后,就可以利用 iconv 或 mb_convert_encoding 来转换编码了。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version
God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download
The most popular open source editor