function แปลง tis620 เป็น utf8 และ utf8 เป็น tis620 ด้วย php


หน้าแรก PHP MySQL เกร็ดความรู้ function แปลง tis620 เป็น utf8 และ utf8 เป็น tis620 ด้วย php
ในการเขียนเวปไซด์บ้างครั้งเรามีความจำเป็นที่จะต้องแปลง unicode ไปมาระหว่าง tis620 เป็น utf8 หรือจาก utf8 เป็น tis620ผมขอยกตัวอย่างเคสที่ต้องเปลี่ยน unicode เช่น db เป็น tis620 แต่หน้าเวปไซด์เรา เป็น utf8 และเราไม่สามารถที่จะเ้ปลี่ยนจาก db เป็น utf8
และเราก็ไม่สามารถเปลี่ยนเวปไซด์เป็น tis620 ได้ เราต้องใช้ function ดังกล่าวเปลี่ยน unicode ครับ

function ในการแปลงจาก tis620 เป็น utf8


  Code
function tis620_to_utf8($tis) {
for( $i=0 ; $i< strlen($tis) ; $i++ ){
$s = substr($tis, $i, 1);
$val = ord($s);
if( $val < 0x80 ){
$utf8 .= $s;
} elseif ((0xA1 <= $val and $val <= 0xDA)
or (0xDF <= $val and $val <= 0xFB)) {
$unicode = 0x0E00 + $val - 0xA0;
$utf8 .= chr( 0xE0 | ($unicode >> 12) );
$utf8 .= chr( 0x80 | (($unicode >> 6) & 0x3F) );
$utf8 .= chr( 0x80 | ($unicode & 0x3F) );
}
}
return $utf8;
}



หรือ


  Code
function ThaiIToUTF8($in) {
$out = "";
for ($i = 0; $i < strlen($in); $i++)
{
if (ord($in[$i]) <= 126)
$out .= $in[$i];
else
$out .= "&#" . (ord($in[$i]) - 161 + 3585) . ";";
}
return $out;
}
// วิธีใช้
echo ThaiToUTF8("ทดสอบ Test");




function ในการแปลงจาก utf8 เป็น tis620


  Code
function utf8_to_tis620($string) {
$str = $string;
$res = "";
for ($i = 0; $i < strlen($str); $i++) {
if (ord($str[$i]) == 224) {
$unicode = ord($str[$i+2]) & 0x3F;
$unicode |= (ord($str[$i+1]) & 0x3F) << 6;
$unicode |= (ord($str[$i]) & 0x0F) << 12;
$res .= chr($unicode-0x0E00+0xA0);
$i += 2;
} else {
$res .= $str[$i];
}
}
return $res;
}



ขึ้นไปด้านบน