This article introduces a piece of code for transcoding and judging string encoding in PHP programming. Friends in need can use it as a reference.
It is often necessary to implement GBK and UTF-8 encoding conversion in PHP. For example, json_encode in PHP itself does not support GBK encoding at all.
There are two library functions that can support encoding conversion. The one that usually comes to mind is the iconv function. For example:
<?php iconv('GBK', 'UTF-8//IGNORE', '芒果小站'); // 将字符串由 GBK 编码转换为 UTF-8 编码 Copy after login <?php mb_detect_encoding('程序员之家'); Copy after login <?php // 使用 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; } } } Copy after login |