PHP method to convert Chinese to unicode

王林
Release: 2023-02-28 17:02:02
Original
4713 people have browsed it

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;
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!