Home  >  Article  >  Backend Development  >  How to convert Chinese to byte in php

How to convert Chinese to byte in php

藏色散人
藏色散人Original
2021-11-17 09:14:352410browse

php method to convert Chinese into byte: 1. Create a PHP sample file; 2. Convert Chinese into byte array through the "function stringToByteArray($str,$charset) {...}" method. Can.

How to convert Chinese to byte in php

The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer

php How to convert Chinese to byte?

php Chinese character byte array conversion

<?php
function stringToByteArray($str,$charset) {
 
    $str = iconv($charset,&#39;UTF-16&#39;,$str);
    preg_match_all(&#39;/(.)/s&#39;,$str,$bytes);  //注:本文的盗版已经有了。不过,提示一下读者,这里的正则改了。
    $bytes=array_map(&#39;ord&#39;,$bytes[1]) ;
    return $bytes;
 
}
 
function byteArrayToString($bytes,$charset) {
 
    $bytes=array_map(&#39;chr&#39;,$bytes);
    $str=implode(&#39;&#39;,$bytes);
    $str = iconv(&#39;UTF-16&#39;,$charset,$str);
    return $str;
 
}
 
$byteArray=stringToByteArray(&#39;13亿人口大国,自认为精通PHP的还是相当多的!&#39;,&#39;utf-8&#39;);
print_r($byteArray);
$retStr=byteArrayToString($byteArray,&#39;utf-8&#39;);
echo $retStr;
 
?>

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to convert Chinese to byte in php. 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