PHP is a widely used server-side scripting language used for web development. It can be used with HTML to create dynamic web pages and web applications. In PHP, converting a string containing multiple values into an array is a common operation. This article will introduce how to use PHP to convert a string containing "&" into an array.
1. Use the explode() function
The explode() function is a function in PHP used to convert a string into an array. It splits the string into array elements and returns them.
For a string containing "&", you can use the explode() function to split it into multiple values. The sample code is as follows:
$str = "apple&banana&orange"; $arr = explode("&", $str); print_r($arr);
The output of the above code is:
Array ( [0] => apple [1] => banana [2] => orange )
2. Use the parse_str() function
The parse_str() function is a function in PHP used to parse URL query strings and convert them into arrays. It allocates the keys and values in the string to the array. The sample code is as follows:
$str = "fruit[]=apple&fruit[]=banana&fruit[]=orange"; parse_str($str, $arr); print_r($arr['fruit']);
The output of the above code is:
Array ( [0] => apple [1] => banana [2] => orange )
3. Use the preg_split() function
The preg_split() function is a function in PHP used to split strings according to regular expression matching patterns. It splits the string into an array and returns it.
For a string containing "&", you can use the preg_split() function to split it into multiple values. The sample code is as follows:
$str = "apple&banana&orange"; $arr = preg_split('/&/', $str); print_r($arr);
The output of the above code is:
Array ( [0] => apple [1] => banana [2] => orange )
Summary
Converting strings containing "&" into arrays is a common requirement in PHP. This article introduces three methods: using the explode() function, using the parse_str() function and using the preg_split() function. Through the use of these functions, developers can easily convert strings into arrays and perform subsequent operations and processing.
The above is the detailed content of How to convert string containing '&' into array in php. For more information, please follow other related articles on the PHP Chinese website!