1.explode Method Description
The Explode method allows a string to be split into groups by one string as a boundary point.
Array explode (string $delimiter, string $string [, int $limit])
Returns an array of strings, each of which is a substring of string, separated by the delimiter as the boundary point.
parameter Description:
delimiter
The delimited character on the boundary.
string
The input string
Limit
If the limit parameter is set and is a positive number, the returned array contains a maximum of limit elements, and the last element will contain the remainder of the string.
If the limit parameter is a negative number, all elements except the last-limit element are returned.
If limit is 0, it will be treated as 1.
2. Example
Use, split string
<?php$str = ' 1,2,3,4,5,6,7,8,9 ', $arr = explode (', ', $str), Echo ' <pre> ';p rint_r ($arr), echo ' </pre> ';? >
Output:
Array ( [0] = 1 [1] = 2 [2] = 3 [3] = 4 [4] = 5 [5] = 6 [6] = = 7
[7] + 8 [8] = 9)
Use, split string, limit is positive
<?php$str = ' 1,2,3,4,5,6,7,8,9 '; $arr = explode (', ', $str, 5), Echo ' <pre> ';p rint_r ($arr), echo ' </pre> ';? >
Output:
Array ( [0] = 1 [1] = 2 [2] = 3 [3] = 4 [4] = 5,6,7,8,9)
Use, split string, negative limit
<?php$str = ' 1,2,3,4,5,6,7,8,9 '; $arr = explode (', ', $str,-3), echo ' <pre> ';p rint_r ($arr), echo ' </pre> ';? >
Output:
Array ( [0] = 1 [1] = 2 [2] = 3 [3] = 4 [4] = 5 [5] = 6)
Use, split string, limit is 0
<?php$str = ' 1,2,3,4,5,6,7,8,9 '; $arr = explode (', ', $str, 0), Echo ' <pre> ';p rint_r ($arr), echo ' </pre> ';? >
Output:
Array ( [0] = 1,2,3,4,5,6,7,8,9)
3. Easy to ignore problems
In general, we use explode to split data such as ID strings.
<?php$ids = ' 1,2,3,4 '; $data = explode (', ', $ids); if ($data) { foreach ($data as $k + = $v) { //do Sth }}? >
Under normal circumstances, IDS is not empty, look at the code will not find any problem, because there is a judgment if (data), it is generally considered to have done an empty processing.
But the reality is ids=null, but data is not empty, causing problems with the code executing in foreach.
<?php$ids = null, $data = Explode (', ', $ids), if ($data) { print_r ($data);} else{ echo ' null ';}? >
Because Ids=null, the array ( [0] = =) instead of array ()is derived using explode.
So the judgment needs to be modified to avoid problems.
<?php$ids = null, $data = Explode (', ', $ids), if (Isset ($data [0]) && $data [0]) { foreach ($data as $k + = $v) { //do sth }}?>
This article explains PHP use explode split string novice easy to ignore the problem, more relevant content please focus on PHP Chinese web.
Related recommendations:
Explanation of two-column data methods in MySQL interchange table
How to generate 0~1 random decimal method via PHP
Instructions for using MySQL timestamp format function from_unixtime