In PHP programming, strings and arrays are common data types. Sometimes, we need to convert a string to an array for data processing. PHP provides many functions to achieve this purpose. This article will explain how to convert a string to an array.
1. Use the explode() function
PHP’s built-in explode() function can split a string into an array according to the specified delimiter. Delimiters can be spaces, commas, semicolons, or other characters.
Syntax: array explode (string $delimiter, string $string [, int $limit = PHP_INT_MAX])
Parameter description:
$delimiter: delimiter
$string: Original string to be split
$limit: Optional parameter, specify the length of the array
Sample code:
$str = "apple,banana,orange,grape"; $arr = explode(",", $str); print_r($arr);
Output result:
Array ( [0] => apple [1] => banana [2] => orange [3] => grape )
2. Use str_split ()Function
str_split() function can split a string into an array of single characters.
Syntax: array str_split ( string $string [, int $split_length = 1 ] )
Parameter description:
$string: The original string to be split
$split_length: Optional parameter, specify the length of each array element
Sample code:
$str = "hello"; $arr = str_split($str); print_r($arr);
Output result:
Array ( [0] => h [1] => e [2] => l [3] => l [4] => o )
3. Use the preg_split() function
with explode( )Similarly, the preg_split() function can also split a string into an array according to the pattern matched by the regular expression.
Syntax: array preg_split ( string $pattern , string $subject [, int $limit = -1 [, int $flags = 0 ]] )
Parameter description:
$pattern : Regular expression
$subject: The original string to be split
$limit: Optional parameter, specifying the length of the array
$flags: Optional parameter, specifying the regular expression pattern
Sample code:
$str = "Hello, world!"; $arr = preg_split('/ |,/', $str); print_r($arr);
Output result:
Array ( [0] => Hello, [1] => world! )
Summary
This article introduces three methods of converting a string into an array in PHP, using explode() and str_split () and preg_split() functions. Different methods need to be selected according to the actual situation. For ordinary string splitting, the explode() function is the most commonly used method. For more complex string splitting, the preg_split() function provides more advanced functionality.
The above is the detailed content of php converts a string into an array. For more information, please follow other related articles on the PHP Chinese website!