Unicode to UTF8 and vice versa

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
localhost
Forum Commoner
Posts: 43
Joined: Tue Dec 07, 2004 4:52 am
Location: islamabad
Contact:

Unicode to UTF8 and vice versa

Post by localhost »

Just something i have searched alot and would like to share
Here is a javascript code for conversion of UTF-8 to Unicode

Code: Select all

<script type=&quote;text/javascript&quote;>
<!--
function unicode() 
  {
  	var src = document.budgetdetail.T1.value;
	var srcLength = src.length;
    var i, c, unicodeString = '';
    var zeros = &quote;0000&quote;;
    for (i = 0; i < srcLength; i++) {
      c = src.charCodeAt(i).toString(16);
      unicodeString += '%u' + zeros.substring(c.length) + c;
    }
    return unicodeString;
  }
//-->
</script>
and to reconvert it here is the code in PHP

Code: Select all

function uni2utf8($uniescape)
{
    $c = "";
    
    $n = intval(substr($uniescape, -4), 16);
    if ($n < 0x7F) {        // 0000-007F
        $c .= chr($n);
    } elseif ($n < 0x800) { // 0080-0800
        $c .= chr(0xC0 | ($n / 64));
        $c .= chr(0x80 | ($n % 64));
    } else {                // 0800-FFFF
        $c .= chr(0xE0 | (($n / 64) / 64));
        $c .= chr(0x80 | (($n / 64) % 64));
        $c .= chr(0x80 | ($n % 64));
    }
    return $c;
}
Post Reply