PHP中Unicode编码转换为UTF-8字符

/**
 * utf8字符转换成Unicode字符
 * @param  [type] $utf8_str Utf-8字符
 * @return [type]           Unicode字符
 */
function utf8_str_to_unicode($utf8_str)
{
    $unicode = (ord($utf8_str[0]) & 0x1F) << 12;
    $unicode |= (ord($utf8_str[1]) & 0x3F) << 6;
    $unicode |= (ord($utf8_str[2]) & 0x3F);
    return dechex($unicode);
}

/**
 * Unicode字符转换成utf8字符
 * @param  [type] $unicode_str Unicode字符
 * @return [type]              Utf-8字符
 */
function unicode_to_utf8($unicode_str)
{
    $code = intval(hexdec($unicode_str));
    //这里注意转换出来的code一定得是整形,这样才会正确的按位操作
    $ord_1 = decbin(0xE0 | ($code >> 12));
    $ord_2 = decbin(0x80 | (($code >> 6) & 0x3F));
    $ord_3 = decbin(0x80 | ($code & 0x3F));
    $utf8_str = chr(bindec($ord_1)) . chr(bindec($ord_2)) . chr(bindec($ord_3));
    return $utf8_str;
}

原文地址:PHP实现Unicode和UTF-8编码的互相转换

你可能感兴趣的:(PHP,php,编码)