PHP: A common function for converting Chinese characters to Unicode

Source: Internet
Author: User

The general function of converting a Chinese character to Unicode does not depend on any library or any other custom function, but conditionally: this file and the input parameters of the function should be encoded with utf-8, otherwise the function conversion should be added.

<?
/**
* A common function that converts a Chinese character to Unicode and does not rely on any libraries, and other custom functions, but conditional
* Conditions: This file and the input parameters of the function should be encoded with utf-8, otherwise the function conversion
* In fact can easily write the function of reverse conversion, Not even limited to Chinese characters, strange why PHP does not have a ready-made function
* @author xieye
*
* @param {string} $word must be a Chinese character, or an array representing Chinese characters (cut with Str_split)
* @re Turn {string} A decimal Unicode code, such as 4f60, representing the Chinese character "you"
/
Function getUnicodeFromOneUTF8 ($word) {
//Get an internal array representation of its characters. So this file applies utf-8 encoding!
if (Is_array ($word))
$arr = $word;
Else
$arr = Str_split ($word);
//At this point, $arr should be similar to array (228, 189, 160)
//define an empty string store
$bin _str = '; The
//turns into a number and turns into a binary string, which is finally combined.
foreach ($arr as $value)
$bin _str. = Decbin (ord ($value));
//At this point, $bin _str should be similar to 111001001011110110100000 if it is the Chinese character "you"
//Regular intercept
$bin _str = preg_replace ('/^.{ 4} (. { 4}). {2} (. {6}). {2} (. {6}) $/', ' $1$2$3 ', $bin _str);
//At this point, the $bin _str should be similar to 0100111101100000 if it is Kanji "you"
Return Bindec ($bin _str);//back to similar 20320, kanji "You"
//return Dechex ( Bindec ($bin _str)); To return to the hexadecimal 4f60, use this sentence
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.