PHP判断字符串是utf-8 还是gb2312并实现utf-8和gb2312自动转化

WBOY
Release: 2016-06-20 13:01:58
Original
770 people have browsed it

判断字符串是utf-8 还是gb2312函数

/**
* 判断字符串是utf-8 还是gb2312
* @param unknown $str
* @param string $default
* @return string
*/
function utf8_gb2312($str, $default = 'gb2312')
{
   $str = preg_replace("/[\x01-\x7F]+/", "", $str);
   if (empty($str)) return $default;
 
   $preg =  array(
       "gb2312" => "/^([\xA1-\xF7][\xA0-\xFE])+$/", //正则判断是否是gb2312
       "utf-8" => "/^[\x{4E00}-\x{9FA5}]+$/u",      //正则判断是否是汉字(utf8编码的条件了),这个范围实际上已经包含了繁体中文字了
   );
 
   if ($default == 'gb2312') {
       $option = 'utf-8';
   } else {
       $option = 'gb2312';
   }
 
   if (!preg_match($preg[$default], $str)) {
       return $option;
   }
   $str = @iconv($default, $option, $str);
 
   //不能转成 $option, 说明原来的不是 $default
   if (empty($str)) {
       return $option;
   }
   return $default;
}
Copy after login

utf-8和gb2312自动转化

/**
* utf-8和gb2312自动转化
* @param unknown $string
* @param string $outEncoding
* @return unknown|string
*/
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) {
// 第一个字节判断通过
$char = $string {++ $i};
if ((ord ( $char ) & 128) == 128) {
// 第二个字节判断通过
$char = $string {++ $i};
if ((ord ( $char ) & 128) == 128) {
$encoding = "UTF-8";
break;
}
}
}
if ((ord ( $string {$i} ) & 192) == 192) {
// 第一个字节判断通过
$char = $string {++ $i};
if ((ord ( $char ) & 128) == 128) {
// 第二个字节判断通过
$encoding = "GB2312";
break;
}
}
}
 
if (strtoupper ( $encoding ) == strtoupper ( $outEncoding ))
return $string;
else
return @iconv ( $encoding, $outEncoding, $string );
}
Copy after login

 


Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template