Created
June 21, 2012 07:18
-
-
Save barlino/2964367 to your computer and use it in GitHub Desktop.
Get the string encoding via mb_detect_encoding()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*** | |
code from http://qiujiayu.iteye.com/blog/565929 | |
*/ | |
<?php | |
define ('UTF32_BIG_ENDIAN_BOM' , chr(0x00) . chr(0x00) . chr(0xFE) . chr(0xFF)); | |
define ('UTF32_LITTLE_ENDIAN_BOM', chr(0xFF) . chr(0xFE) . chr(0x00) . chr(0x00)); | |
define ('UTF16_BIG_ENDIAN_BOM' , chr(0xFE) . chr(0xFF)); | |
define ('UTF16_LITTLE_ENDIAN_BOM', chr(0xFF) . chr(0xFE)); | |
define ('UTF8_BOM' , chr(0xEF) . chr(0xBB) . chr(0xBF)); | |
function detect_utf_encoding($text) { | |
$first2 = substr($text, 0, 2); | |
$first3 = substr($text, 0, 3); | |
$first4 = substr($text, 0, 3); | |
if ($first3 == UTF8_BOM) return 'UTF-8'; | |
elseif ($first4 == UTF32_BIG_ENDIAN_BOM) return 'UTF-32BE'; | |
elseif ($first4 == UTF32_LITTLE_ENDIAN_BOM) return 'UTF-32LE'; | |
elseif ($first2 == UTF16_BIG_ENDIAN_BOM) return 'UTF-16BE'; | |
elseif ($first2 == UTF16_LITTLE_ENDIAN_BOM) return 'UTF-16LE'; | |
} | |
function getFileEncoding($str){ | |
$list = array("ASCII", "BIG5", "GB2312", "GBK", "UTF-8"); | |
$encoding=mb_detect_encoding($str, $list); | |
if(empty($encoding)){ | |
$encoding=detect_utf_encoding($str); | |
} | |
return $encoding; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment