In PHP, string is a very common data type. In some cases, we need to convert strings into arrays for easy operation and processing. This process can be accomplished through PHP's built-in functions. This article will introduce several methods of converting strings into arrays.
1. Convert a string into a character array
In PHP, we can use the str_split() function to convert a string into an array of characters. The following is an example:
$string = "Hello world!"; $array = str_split($string); print_r($array);
Output result:
Array ( [0] => H [1] => e [2] => l [3] => l [4] => o [5] => [6] => w [7] => o [8] => r [9] => l [10] => d [11] => ! )
We can see that the string is divided into characters and placed in the array. If we need to split the string into multiple characters and then perform some operations, then this method can play a big role.
2. Convert a string into an array
In PHP, a string can also be separated into multiple strings by some specific symbols and put into an array. Two methods are introduced here, namely explode() and preg_split() functions.
explode() function can split a string into an array by using a specific delimiter. The following is an example:
$string = "apple,banana,orange"; $array = explode(",", $string); print_r($array);
Output result:
Array ( [0] => apple [1] => banana [2] => orange )
In this example, we divide the $string string into three strings according to the comma separator, and place these strings in the array.
preg_split() function is similar to the explode() function. It can split a string into multiple characters through specific delimiters. strings and put these strings into an array. Unlike explode(), the preg_split() function can use regular expressions as delimiters. The following is an example:
$string = "apple,banana.orange,grape"; $array = preg_split("/[,.]/", $string); print_r($array);
Output result:
Array ( [0] => apple [1] => banana [2] => orange [3] => grape )
In this example, we use a regular expression, using "," and "." as delimiters to separate the string Split into four strings. As you can see, using the preg_split() function allows you to process strings more flexibly.
Summary
In PHP, strings and arrays are two common data types. Through the above introduction, we can convert strings into arrays and perform related operations and processing. Of course, in actual development, the specific method must be selected according to the actual situation.
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!