Just in case the comment about empty strings is not clear:
<?php
$a = array();
var_dump($a);
$s = implode("\n", $a);
var_dump($s);
$b = explode("\n", $s);
var_dump($b);
$b = preg_split('/\n/', $s,-1,PREG_SPLIT_NO_EMPTY);
var_dump($b);
?>
Results in:
array(0) {
}
string(0) ""
array(1) {
[0]=>
string(0) ""
}
array(0) {
}
i.e. exploding an empty string results in an array with one element. You can use preg_split to skip the empty item, but that may not be quite what you need should your array have empty elements intentionally.
explode
(PHP 4, PHP 5)
explode — Split a string by string
Description
Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter .
Parameters
- delimiter
-
The boundary string.
- string
-
The input string.
- limit
-
If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string .
If the limit parameter is negative, all components except the last -limit are returned.
If the limit parameter is zero, then this is treated as 1.
Although implode() can, for historical reasons, accept its parameters in either order, explode() cannot. You must ensure that the delimiter argument comes before the string argument.
Return Values
If delimiter is an empty string (""), explode() will return FALSE. If delimiter contains a value that is not contained in string and a negative limit is used, then an empty array will be returned. For any other limit , an array containing string will be returned.
Changelog
| Version | Description |
|---|---|
| 5.1.0 | Support for negative limit s was added |
| 4.0.1 | The limit parameter was added |
Examples
Example #1 explode() examples
<?php
// Example 1
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
// Example 2
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);
echo $user; // foo
echo $pass; // *
?>
Example #2 limit parameter examples
<?php
$str = 'one|two|three|four';
// positive limit
print_r(explode('|', $str, 2));
// negative limit (since PHP 5.1)
print_r(explode('|', $str, -1));
?>
The above example will output:
Array
(
[0] => one
[1] => two|three|four
)
Array
(
[0] => one
[1] => two
[2] => three
)
Notes
Note: This function is binary-safe.
See Also
- preg_split() - Split string by a regular expression
- str_split() - Convert a string to an array
- str_word_count() - Return information about words used in a string
- strtok() - Tokenize string
- implode() - Join array elements with a string
explode
15-Jun-2009 07:20
21-Apr-2009 08:20
Keep in mind that explode() can return empty elements if the delimiter is immediately repeated twice (or more), as shown by the following example:
<?php
$foo = 'uno dos tres'; // two spaces between "dos" and "tres"
print_r(explode(' ', $foo));
?>
Array
(
[0] => uno
[1] => dos
[2] =>
[3] => tres
)
Needless to say this is definitely not intuitive and must be handled carefully.
19-Apr-2009 02:59
Here's a simple script which uses explode() to check to see if an IP address is in an array (can be used as a ban-check, without needing to resort to database storage and queries).
<?php
function denied($one) {
$denied = array(
0 => '^255.255.255.255',
1 => '^255.250',
2 => '^255.255.250'
);
for ($i = 0 ; $i < sizeof($denied) ; $i++) {
if (sizeof(explode($denied[$i], '^' . $one . '$')) == 2) {
return true;
}
}
return false;
}
if (denied($_SERVER['REMOTE_ADDR'])) {
header('Location: denied.php');
}
?>
31-Mar-2009 05:33
<?php
function my_explode($delim, $str, $lim = 1)
{
if ($lim > -2) return explode($delim, $str, abs($lim));
$lim = -$lim;
$out = explode($delim, $str);
if ($lim >= count($out)) return $out;
$out = array_chunk($out, count($out) - $lim + 1);
return array_merge(array(implode($delim, $out[0])), $out[1]);
}
?>
This function can assume `limit' parameter less than 0, for example:
<?php
print_r(my_explode('.', 'file.some.ext.jpg', -2));
?>
prints
Array
(
[0] => file.some.ext
[1] => jpg
)
24-Feb-2009 04:10
<?php
function explode_escaped($delimiter, $string){
$exploded = explode($delimiter, $string);
$fixed = array();
for($k = 0, $l = count($exploded); $k < $l; ++$k){
if($exploded[$k][strlen($exploded[$k]) - 1] == '\\') {
if($k + 1 >= $l) {
$fixed[] = trim($exploded[$k]);
break;
}
$exploded[$k][strlen($exploded[$k]) - 1] = $delimiter;
$exploded[$k] .= $exploded[$k + 1];
array_splice($exploded, $k + 1, 1);
--$l;
--$k;
} else $fixed[] = trim($exploded[$k]);
}
return $fixed;
}
?>
Here's a function which explodes string with delimiter, but if delimiter is "escaped" by backslash, function won't split in that point. Example:
<?php
$result = explode_escaped(',', 'string, piece, group\, item\, item2, next\,asd');
print_r($result);
?>
Will give:
Array
(
[0] => string
[1] => piece
[2] => group, item, item2
[3] => next,asd
)
05-Dec-2008 10:32
<?php
// Remove words if more than max allowed character are insert or add a string in case less than min are displayed
// Example: LimitText("The red dog ran out of thefence",15,20,"<br>");
function LimitText($Text,$Min,$Max,$MinAddChar) {
if (strlen($Text) < $Min) {
$Limit = $Min-strlen($Text);
$Text .= $MinAddChar;
}
elseif (strlen($Text) >= $Max) {
$words = explode(" ", $Text);
$check=1;
while (strlen($Text) >= $Max) {
$c=count($words)-$check;
$Text=substr($Text,0,(strlen($words[$c])+1)*(-1));
$check++;
}
}
return $Text;
}
?>
17-Nov-2008 07:08
A really better and shorter way to get extension is via:
<?php $extension = end(explode('.', $filename)); ?>
this will print the last part after the last dot :)
30-Aug-2008 12:54
For anyone trying to get an array of key => value pairs from a query string, use parse_str. (Better alternative than the explode_assoc function listed way down the page unless you need different separators.)
15-Oct-2007 02:56
coroa at cosmo-genics dot com mentioned using preg_split() instead of explode() when you have multiple delimiters in your text and don't want your result array cluttered with empty elements. While that certainly works, it means you need to know your way around regular expressions... and, as it turns out, it is slower than its alternative. Specifically, you can cut execution time roughly in half if you use array_filter(explode(...)) instead.
Benchmarks (using 'too many spaces'):
Looped 100000 times:
preg_split: 1.61789011955 seconds
filter-explode: 0.916578054428 seconds
Looped 10000 times:
preg_split: 0.162719011307 seconds
filter-explode: 0.0918920040131 seconds
(The relation is, evidently, pretty linear.)
Note: Adding array_values() to the filter-explode combination, to avoid having those oft-feared 'holes' in your array, doesn't remove the benefit, either. (For scale - the '9' becomes a '11' in the benchmarks above.)
Also note: I haven't tested anything other than the example with spaces - since djogo_curl at yahoo's note seems to imply that explode() might get slow with longer delimiters, I expect this would be the case here, too.
I hope this helps someone. :)
10-Dec-2006 09:19
Note that explode, split, and functions like it, can accept more than a single character for the delimiter.
<?php
$string = "Something--next--something else--next--one more";
print_r(explode('--next--',$string));
?>
01-Dec-2004 06:20
Being a beginner in php but not so in Perl, I was used to split() instead of explode(). But as split() works with regexps it turned out to be much slower than explode(), when working with single characters.
16-Nov-2003 09:31
To split a string containing multiple seperators between elements rather use preg_split than explode:
preg_split ("/\s+/", "Here are to many spaces in between");
which gives you
array ("Here", "are", "to", "many", "spaces", "in", "between");
