Home > Backend Development > PHP Tutorial > [原创]PHP字符串与字节数组的高速互换

[原创]PHP字符串与字节数组的高速互换

WBOY
Release: 2016-06-13 13:04:45
Original
997 people have browsed it

[原创]PHP字符串与字节数组的快速互换

??????? 要加密,则需要将字符串转为ASCII的字节数组。反之,则要转回来。代码为什么速度快?那就是,能不用FOR循环的,直接不用。使用PHP原有的函数,让它实现,这是最快的。

<?php function stringToByteArray($str,$charset) {

    $str = iconv($charset,'UTF-16',$str);
    preg_match_all('/(.)/s',$str,$bytes);  //注:本文的盗版已经有了。不过,提示一下读者,这里的正则改了。
    $bytes=array_map('ord',$bytes[1]) ;
    return $bytes;

}

function byteArrayToString($bytes,$charset) {

    $bytes=array_map('chr',$bytes);
    $str=implode('',$bytes);
    $str = iconv('UTF-16',$charset,$str);
    return $str;

}

$byteArray=stringToByteArray('13亿人口大国,自认为精通PHP的还是相当多的!','utf-8');
print_r($byteArray);
$retStr=byteArrayToString($byteArray,'utf-8');
echo $retStr;

?>
Copy after login

?

每个函数只有4行代码,没有FOR循环,但当文本相当长时,你就能发现,差别真的很大。

?

?

注:希望各位读者注意:本人博文如未注明是转发,全系本人原创。网上盗用版本甚多。但由于博文在发布时,有可能是多次编辑增加内容,或因有瑕疵而需要修改。所以,请来这里查看原创正版。

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