In PHP programming, we often need to convert strings into byte arrays. In this article, we will introduce how to convert characters into byte array in PHP.
1. Use str_split() function
PHP built-in function str_split() can split a string into a character array. This function passes a string as the first parameter, and the second parameter specifies the length of each group. If the second parameter is not specified, the default length is 1. The following is an example of converting a string into a byte array:
$str = "Hello World"; $bytes = str_split($str); print_r($bytes);
The output result is as follows:
Array ( [0] => H [1] => e [2] => l [3] => l [4] => o [5] => [6] => W [7] => o [8] => r [9] => l [10] => d )
We can see that the str_split() function has successfully converted the string into Byte array.
2. Use the unpack() function
PHP built-in function unpack() can divide the binary string into different variables. We can use this function to convert a string into a byte array. The following is an example:
$str = "Hello World"; $bytes = unpack('C*', $str); print_r($bytes);
The output is as follows:
Array( [1] => 72 [2] => 101 [3] => 108 [4] => 108 [5] => 111 [6] => 32 [7] => 87 [8] => 111 [9] => 114 [10] => 108 [11] => 100 )
We can see that the unpack() function has successfully converted the string into a byte array.
3. Use the mb_str_split() function
If the string we process contains multi-byte characters, we can use the mb_str_split() function to convert the string into a byte array. The following is an example:
$str = "你好世界"; $bytes = preg_split('//u', $str, -1, PREG_SPLIT_NO_EMPTY); foreach($bytes as &$byte) { $byte = bin2hex(mb_convert_encoding($byte, 'UCS-2BE')); } print_r($bytes);
The output is as follows:
Array ( [0] => 4f60 [1] => 597d [2] => 4e16 [3] => 754c )
We can see that the mb_str_split() function has successfully converted a string containing multi-byte characters into a byte array .
The above are three methods of converting characters into byte arrays in PHP. We can choose different methods to implement this function according to our needs.
The above is the detailed content of How to convert php characters into byte array. For more information, please follow other related articles on the PHP Chinese website!