The explode() function can split a string into an array.
Syntax: explode(separator,string,limit).
This function returns an array composed of strings, each element of which is a substring separated by separator as a boundary point.
The separator parameter cannot be an empty string. If separator is the empty string (""), explode() returns FALSE. If separator contains a value that is not found in string, explode() returns an array containing a single element from string.
If the limit parameter is set, the returned array contains at most limit elements, and the last element will contain the remainder of the string.
If the limit parameter is negative, all but the last -limit elements are returned. This feature is new in PHP 5.1.0.
<?php // Example 1 $fruit = "Apple Banana Orange Lemon Mango Pear"; $fruitArray = explode(" ", $fruit); echo $fruitArray[0]; // Apple echo $fruitArray[1]; // Banana // Example 2 $data = "gonn:*:bkjia:1000::/home/foo:/bin/sh"; list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data); echo $user; // gonn echo $pass; // * ?>
Program execution result:
Apple Banana gonn *
<?php $str = 'one|two|three|four'; // positive limit print_r(explode('|', $str, 2)); // negative limit (since PHP 5.1) print_r(explode('|', $str, -1)); ?>
Program execution result:
Array ( [0] => one [1] => two|three|four ) Array ( [0] => one [1] => two [2] => three )
<?php // converts pure string into a trimmed keyed array function string2KeyedArray($string, $delimiter = ',', $kv = '=>') { if ($a = explode($delimiter, $string)) { // create parts foreach ($a as $s) { // each part if ($s) { if ($pos = strpos($s, $kv)) { // key/value delimiter $ka[trim(substr($s, 0, $pos))] = trim(substr($s, $pos + strlen($kv))); } else { // key delimiter not found $ka[] = trim($s); } } } return $ka; } } // string2KeyedArray $string = 'a=>1, b=>23, $a, c=>45%, true, d=>ab c'; print_r(string2KeyedArray($string)); ?>
Program execution result:
Array ( [a] => 1 [b] => 23 [0] => $a [c] => 45% [1] => true [d] => ab c )