标签归档:Unicode编码

对汉字进行Unicode编码

/**
 * 对汉字进行Unicode编码 (#21704;哈)
 * @param $str 汉字字符串
 * @param $code 汉字字符串的编码,默认utf-8
 */
function uni_encode ($str, $code = 'utf-8'){
    if($code != 'utf-8'){
        $str = iconv($code, 'utf-8', $str);
    }
    $str = json_encode($str);
    $str = preg_replace_callback('/\\\\u(\w{4})/', create_function('$hex', 'return \'&#\'.hexdec($hex[1]).\';\';'), substr($str, 1, strlen($str)-2));
    return $str;
}

/**
 * 对Unicode编码进行解码
 * @param $str Unicode编码的字符串
 * @param $code 返回汉字字符串的编码,默认utf-8
 */
function uni_decode ($str, $code = 'utf-8'){
    $str = json_decode(preg_replace_callback('/&#(\d{5});/', create_function('$dec', 'return \'\\u\'.dechex($dec[1]);'), '"'.$str.'"'));
    if($code != 'utf-8'){
        $str = iconv('utf-8', $code, $str);
    }
    return $str;
}