search
HomeBackend DevelopmentPHP TutorialUnicode encoding converter php utf-8 to unicode function page 1/2

UTF encoding
UTF-8 encodes UCS in 8-bit units. The encoding method from UCS-2 to UTF-8 is as follows:
UCS-2 encoding (hexadecimal)
UTF-8 byte stream (binary)
0000 - 007F
0xxxxxxx
0080 - 07FF
110xxxxx 10xxxxxx
0800 - FFFF
1110xxxx 10xxxxxx 10xxxxxx
For example, the Unicode encoding of the "Chinese" character is 6C49. 6C49 is between 0800-FFFF, so you must use a 3-byte template: 1110xxxx 10xxxxxx 10xxxxxx. Writing 6C49 in binary is: 0110 110001 001001. Using this bit stream to replace x in the template in turn, we get: 11100110 10110001 10001001, which is E6 B1 89.
Finally completed the conversion between unicode and utf8.
If the utf-8 encoded character ch is 3 bytes. xx yy zz
AND xx and 1F to get a
AND yy and 7F to get b
AND zz and 7F to get c
(64a+b)*64+c = ch (unicode encoding)
echo.php nothing. Just a few functions.
");
//Write unicode file
$ucs2data = utf8ToUnicode($data,"little");
$endian = chr(0xFE).chr(0xFF);
$endian = chr(0xFF).chr( 0xFE);
$rt = file_put_contents ("ucs2.txt", $endian.$ucs2data);
//19:32, utf8toUnicode function ok.
//20:09. Discover the little endian and big endian problems and solve them. .
//Unicode strings stored in big endian mode cannot be recognized by ue or editplus.
$rt = file_put_contents ("usc2ys_data.txt", $ucs2_ysdata);
//Write. utf8 file
$utf8data = unicodeToUtf8($ucs2data); // 20:52. Convert the string back to utf8 code ok.
$rt = file_put_contents ( "utf8.txt", $utf8data);
echo(urlencode($utf8data ));echo("");
$esc = utf8Escape($data);
echot($esc);
$esc = phpEscape($data);
echot($esc);
$unesc = phpUnescape($ esc);
echot($unesc);
/**
* This function converts utf8 encoded string to unicode encoded string
* Parameter str, utf8 encoded string.
* Parameter order, the data storage format, whether big endian or little endian, the default unicode storage order is little.
* For example: the unicode code of "big" is 5927. Storage in little mode is: 27 59. In big mode, the order remains unchanged: 59 27.
* Little format files must have FF FE at the beginning. Files stored in big format start with FE FF. otherwise. There will be serious confusion.
* This function only converts characters and is not responsible for adding headers.
* The string converted by iconv is stored in big endian.
* Returns ucs2string, the converted string.
* Thanks for nagging (xuzuning)
*/
function utf8ToUnicode($str,$order="little")
{
$ucs2string ="";
$n=strlen($str );
for ($i=0;$i0x80) { //110xxxxx 10xxxxxx
$a = (ord($str[$i]) & 0x3F )0x80 && ord($str[$i+2])> 0x80) { //1110xxxx 10xxxxxx 10xxxxxx
$a = (ord($str[$i]) & 0x1F) Convert to utf8 encoded string
* Parameter str, unicode encoded string
* Parameter order, unicode string. The storage order is big endian or little endian.
* Returns utf8string, the converted string.
*
*/
function unicodeToUtf8($str,$order="little")
{
$utf8string ="";
$n=strlen($str);
for ($i=0;$i turn back .
$i++; //Two bytes represent a unicode character.
$c = "";
if($val utf8string .= $c;
}
return $utf8string;
} // end func
/*
* Encode the utf8 encoded string into unicode pattern, which is equivalent to escape
* The reason why only utf8 code is accepted is because there is only formula conversion between utf8 code and unicode, other codes must be converted by looking up the code table
*. I don’t know if the regular way to find utf8 codes is completely confusing.
* Although calling utf2ucs to calculate the code value of each character is too inefficient. However, the code is clear, and it is not easy to embed the calculation process. Read.
*/
function utf8Escape($str) {
preg_match_all("/[\xC0-\xE0].|[\xE0-\xF0]..|[\x01-\x7f]+/",$ str,$r);
//prt($r);
$ar = $r[0];
foreach($ar as $k=>$v) {
$ord = ord($v[0 ]);
if( $ordutf8 code
$ar[$k] = "%u".utf2ucs($v);
}
elseif ($ordutf8 code
$ar[$k] = "%u".utf2ucs ($v);
}
}//foreach
return join("",$ar);
}
/**
*
* Convert utf8 encoded characters to ucs-2 encoding
* Parameter utf8 encoded characters .
* Returns the unicode code value of the character. Once you know the code value, you can use chr to get the character.
*
* Principle: The algorithm for converting unicode to utf-8 code is.
The reverse algorithm of this process is this function, the fixed head position and the inverse sum.
*/
function utf2ucs($str){
$n=strlen($str);
if ($n=3) {
$highCode = ord($str[0]);
$midCode = ord($ str[1]);
$lowCode = ord($str[2]);
$a = 0x1F & $highCode;
$b = 0x7F & $midCode;
$c = 0x7F & $lowCode;
$ucsCode = (64*$a + $b)*64 + $c;
}
elseif ($n==2) {
$highCode = ord($str[0]);
$lowCode = ord($str[1 ]);
$a = 0x3F & $highCode; //0x3F is the complement of 0xC0
$b = 0x7F & $lowCode; //0x7F is the complement of 0x80
$ucsCode = 64*$a + $b;
}
elseif($n==1) {
$ucscode = ord($str);
}
return dechex($ucsCode);
}
/*
* Usage: This function is used to reverse the encoding of javascript's escape function characters after.
* I don’t know if there is any problem with the key regular search.
* Parameter: JavaScript encoded string.
* Such as: unicodeToUtf8("%u5927")= big
* 2005-12-10
*
*/
function phpUnescape($escstr){
preg_match_all("/%u[0-9A-Za-z]{ 4}|%.{2}|[0-9a-zA-Z.+-_]+/",$escstr,$matches); //prt($matches);
$ar = &$matches[0 ];
$c = "";
foreach($ar as $val){
if (substr($val,0,1)!="%") { //If it is alphanumeric +-_.ascii Code
$c .=$val;
}
elseif (substr($val,1,1)!="u") { //If it is a non-alphanumeric +-_. ascii code
$x = hexdec(substr ($val,1,2));
$c .=chr($x);
}
else { //If it is a code greater than 0xFF
$val = intval(substr($val,2),16) ;
if($val %u".bin2hex( iconv( 'gbk' ,"UCS-2",$chars[$i].$chars[$i+1] ) );
$i++;
}
} //foreach
return $ar;
}
?>

Current page 1/2 12Next page

The above introduces the unicode encoding converter PHP utf-8 to unicode function page 1/2, including the content of the unicode encoding converter. I hope it will be helpful to friends who are interested in PHP tutorials.

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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.