>  기사  >  백엔드 개발  >  PHP 중국어 인코딩 판단 샘플 코드

PHP 중국어 인코딩 판단 샘플 코드

怪我咯
怪我咯원래의
2017-07-06 10:51:371228검색

php는 중국어를 결정하고 인코딩은 gbk가 2바이트이고, utf8은 중국어의 범위에 따라 판단할 수 있습니다.

인코딩 범위 1. GBK(GB2312/GB18030)
x00-xff GBK 2바이트. 인코딩 범위
x20-x7f ASCII
xa1-xff 중국어
x80-xff 중국어
2.UTF-8(유니코드)
u4e00-u9fa5(중국어)
x3130-x318F(한국어
xAC00-xD7A3(한국어)
u 0800 -u4e00(일본어)
ps: 한국어 문자가 [u9fa5]보다 큽니다
일반적인 예:
preg_replace("/([x80-xff])/","",$str)
preg_replace("/( [u4e00 -u9fa5])/”,””,$str)
2. 코드 예

코드는 다음과 같습니다.

//判断内容里有没有中文-GBK (PHP) 
function check_is_chinese($s){ 
return preg_match('/[\x80-\xff]./', $s); 
} 
//获取字符串长度-GBK (PHP) 
function gb_strlen($str){ 
$count = 0; 
for($i=0; $i<strlen($str); $i++){ 
$s = substr($str, $i, 1); 
if (preg_match("/[\x80-\xff]/", $s)) ++$i; 
++$count; 
} 
return $count; 
} 
//截取字符串字串-GBK (PHP) 
function gb_substr($str, $len){ 
$count = 0; 
for($i=0; $i<strlen($str); $i++){ 
if($count == $len) break; 
if(preg_match("/[\x80-\xff]/", substr($str, $i, 1))) ++$i; 
++$count; 
} 
return substr($str, 0, $i); 
} 
//统计字符串长度-UTF8 (PHP) 
function utf8_strlen($str) { 
$count = 0; 
for($i = 0; $i < strlen($str); $i++){ 
$value = ord($str[$i]); 
if($value > 127) { 
$count++; 
if($value >= 192 && $value <= 223) $i++; 
elseif($value >= 224 && $value <= 239) $i = $i + 2; 
elseif($value >= 240 && $value <= 247) $i = $i + 3; 
else die(&#39;Not a UTF-8 compatible string&#39;); 
} 
$count++; 
} 
return $count; 
} 
//截取字符串-UTF8(PHP) 
function utf8_substr($str,$position,$length){ 
$start_position = strlen($str); 
$start_byte = 0; 
$end_position = strlen($str); 
$count = 0; 
for($i = 0; $i < strlen($str); $i++){ 
if($count >= $position && $start_position > $i){ 
$start_position = $i; 
$start_byte = $count; 
} 
if(($count-$start_byte)>=$length) { 
$end_position = $i; 
break; 
} 
$value = ord($str[$i]); 
if($value > 127){ 
$count++; 
if($value >= 192 && $value <= 223) $i++; 
elseif($value >= 224 && $value <= 239) $i = $i + 2; 
elseif($value >= 240 && $value <= 247) $i = $i + 3; 
else die(&#39;Not a UTF-8 compatible string&#39;); 
} 
$count++; 
} 
return(substr($str,$start_position,$end_position-$start_position)); 
} 
//判断是否是有韩文-UTF-8 (JavaScript) 
function checkKoreaChar(str) { 
for(i=0; i<str.length; i++) { 
if(((str.charCodeAt(i) > 0x3130 && str.charCodeAt(i) < 0x318F) || (str.charCodeAt(i) >= 0xAC00 && str.charCodeAt(i) <= 0xD7A3))) { 
return true; 
} 
} 
return false; 
} 
//判断是否有中文字符-GBK (JavaScript) 
function check_chinese_char(s){ 
return (s.length != s.replace(/[^\x00-\xff]/g,"**").length); 
}

위 내용은 PHP 중국어 인코딩 판단 샘플 코드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.