Home > Backend Development > PHP Problem > How to convert Chinese to byte in php

How to convert Chinese to byte in php

藏色散人
Release: 2023-03-13 20:58:01
Original
2444 people have browsed it

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

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!

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