Home > Article > Backend Development > How to convert string to array in php
In the process of PHP programming, we often need to convert strings into arrays to process data more conveniently. Below we will introduce several common methods of converting PHP strings to arrays.
Method 1: Use the explode function
Using the explode function is the most commonly used method to convert a PHP string into an array. It can divide the string according to the specified delimiter and return an array.
Sample code:
$str = 'apple,orange,banana'; $arr = explode(',', $str); print_r($arr);
Output result:
Array ( [0] => apple [1] => orange [2] => banana )
Method 2: Use the str_split function
The str_split function can divide the string according to the specified length , and returns an array.
Sample code:
$str = 'hello world'; $arr = str_split($str); print_r($arr);
Output result:
Array ( [0] => h [1] => e [2] => l [3] => l [4] => o [5] => [6] => w [7] => o [8] => r [9] => l [10] => d )
Method 3: Use the preg_split function
The preg_split function can split the string according to the regular expression points and returns an array. This method is more flexible and can adjust the regular expression according to different situations.
Sample code:
$str = '1a2b3c4d5e'; $arr = preg_split('/\d/', $str); print_r($arr);
Output result:
Array ( [0] => a [1] => b [2] => c [3] => d [4] => e )
Method 4: Use the str_replace function
The str_replace function can replace the specified characters in the string with another character and returns a new string. We can replace the character to be replaced with a comma, and then use the explode function to convert it into an array.
Sample code:
$str = '1-2-3-4-5'; $str = str_replace('-', ',', $str); $arr = explode(',', $str); print_r($arr);
Output result:
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
Method 5: Use json_decode function
If our string conforms to json format, then We can convert it to an array using the json_decode function.
Sample code:
$str = '{"name":"Tom","age":18}'; $arr = json_decode($str, true); print_r($arr);
Output result:
Array ( [name] => Tom [age] => 18 )
Summary
The above are several common methods of converting PHP strings to arrays. We can use Choose the most appropriate method for the actual situation. It is worth noting that when using the explode function or preg_split function to split a string, if the split result contains spaces or other invalid characters, filtering or processing is required to obtain the correct array.
The above is the detailed content of How to convert string to array in php. For more information, please follow other related articles on the PHP Chinese website!