字符串和字节数组的相互转换

<?php
/**
 * 字符串转字节数组
 *
 * @param string $str 字符串
 * @return array 字节数组
 */
function str_to_byte($str)
{
    $byte = [];

    for ($i = 0, $len = strlen($str); $i < $len; $i++) {
        $byte[] = ord($str[$i]);
    }

    return $byte;
}

/**
 * 字节数组转字符串
 *
 * @param array $byte 字节数组
 * @return string 字符串
 */
function byte_to_str($byte)
{
    $str = '';

    foreach ($byte as $value) {
        $str .= chr($value);
    }

    return $str;
}

$byte = str_to_byte('PHP是世界上最好の语言');
print_r($byte);
/********** 输出结果·开始 **********
Array
(
    [0] => 80
    [1] => 72
    [2] => 80
    [3] => 230
    [4] => 152
    [5] => 175
    [6] => 228
    [7] => 184
    [8] => 150
    [9] => 231
    [10] => 149
    [11] => 140
    [12] => 228
    [13] => 184
    [14] => 138
    [15] => 230
    [16] => 156
    [17] => 128
    [18] => 229
    [19] => 165
    [20] => 189
    [21] => 227
    [22] => 129
    [23] => 174
    [24] => 232
    [25] => 175
    [26] => 173
    [27] => 232
    [28] => 168
    [29] => 128
)
********** 输出结果·结束 **********/

$str = byte_to_str($byte);
var_dump($str); // string(30) "PHP是世界上最好の语言"

Copyright © 2024 码农人生. All Rights Reserved