Home >Backend Development >PHP Problem >How to convert string to array in php
Conversion method: 1. Using the explode() function, you can use one string to split another string and return an array composed of strings. The syntax format is "explode('separator', string) "; 2. Use str_split() function, syntax "str_split (string)".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
Method 1: Use explode() Function
<?php header('content-type:text/html;charset=utf-8'); $str = 'PHP中文网,PHP教程,//m.sbmmt.com/,explode()函数,字符串转数组'; echo '<pre class="brush:php;toolbar:false">'; $arr = explode(',', $str); print_r($arr); $arr = explode(',', $str, 3); print_r($arr); $arr = explode(',', $str, -2); print_r($arr); $arr = explode(',', $str, 0); print_r($arr); ?>
Rendering:
Description:
explode() function can be based on string delimiter Split a string, that is, it splits a string into several substrings based on the delimiter, and then combines these substrings into an array and returns it. The syntax format is as follows:
explode(separator,string,limit)
Parameters
delimiter: delimiter character used to split strings;
string: The string that needs to be split;
limit: Optional parameter, which can be empty, specifies the number of array elements to be returned;
If limit is not empty and is a positive number, the returned array contains at most limit elements, and the last element contains the remaining part of string;
If limit is not empty and If it is a negative number, all elements except the last limit elements will be returned;
If limit is 0, it will be treated as 1;
If limit is empty, it means returning all array elements.
If delimiter is an empty string "
", the program will prompt a Warning, and the explode() function will return FALSE; if delimiter The contained value is not found in string and a negative limit is used, an empty array is returned, otherwise an array containing a single element of string is returned.
Method 2: Use str_split() function
<?php $str='woxihuanphp'; echo '<pre class="brush:php;toolbar:false">'; $arr = str_split($str); print_r($arr); ?>
Description:
str_split() function separates characters Split the string into an array.
Syntax
str_split(string,length)
Parameters | Description |
---|---|
string | Required. Specifies the string to be split. |
length | Optional. Specifies the length of each array element. The default is 1. |
Recommended study: "PHP Video Tutorial"
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!