Home  >  Article  >  Backend Development  >  PHP method to convert Chinese to unicode

PHP method to convert Chinese to unicode

王林
王林Original
2019-12-05 10:13:104941browse

PHP method to convert Chinese to unicode

Related function description:

iconv command is used to convert the encoding of the file. For example, it can convert UTF8 encoding to GB18030 encoding, and vice versa.

str_split() Function splits a string into an array.

bin2hex() Function converts a string of ASCII characters to a hexadecimal value. Strings can be converted back using the pack() function.

hexdec() Function converts a hexadecimal number into a decimal number.

Free video tutorial recommendations: php video tutorial

Examples are as follows:

/**
 * $str 原始中文字符串
 * $encoding 原始字符串的编码,默认GBK
 * $prefix 编码后的前缀,默认"&#"
 * $postfix 编码后的后缀,默认";"
 */
function unicode_encode($str, $encoding = 'GBK', $prefix = '&#', $postfix = ';') {
    $str = iconv($encoding, 'UCS-2', $str);
    $arrstr = str_split($str, 2);
    $unistr = '';
    for($i = 0, $len = count($arrstr); $i < $len; $i++) {
        $dec = hexdec(bin2hex($arrstr[$i]));
        $unistr .= $prefix . $dec . $postfix;
    }
    return $unistr;
}

Related article tutorial recommendations: php tutorial

The above is the detailed content of PHP method to convert Chinese to unicode. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn