<?php
/*
This function recursively explodes a string at the boundaries of the strings within the array delimiters
One possible scenario: You concatenated rows and columns with GROUP_CONCAT() in MySQL and want to access the values in an array in PHP
@author Tobias Schultze
@date 2008-07-07
*/
function explode_recursive($delimiters, $string) {
if (!is_array($delimiters)) {
$delimiters = array($delimiters);
}
$delimiter = array_shift($delimiters);
if (!empty($delimiters))
{
$arExploded = explode($delimiter, $string);
if ($arExploded !== false) {
foreach ($arExploded as $key => $value) {
$arExploded[$key] = explode_recursive($delimiters, $value);
}
}
return $arExploded;
}
else
{
return explode($delimiter, $string);
}
}
// Examples:
$strSimpleText = 'row 0 column 0--row 0 column 1--row 0 column 2__row 1 column 0--row 1 column 1--row 1 column 2__row 2 column 0--row 2 column 1--row 2 column 2';
$arSimpleDelimiters = array('__','--');
var_dump(explode_recursive($arSimpleDelimiters, $strSimpleText));
$strComplexText = 'item 0.0.0,item 0.0.1,item 0.0.2;item 0.1.0,item 0.1.1;item 0.2.0,item 0.2.1,item 0.2.2,item 0.2.3|item 1.0.0;item 1.1.0|item 2.0.0,item 2.0.1|item 3.0.0;item 3.1.0,item 3.1.1';
$arComplexDelimiters = array('|',';',',');
var_dump(explode_recursive($arComplexDelimiters, $strComplexText));
// Output:
array(3) {
[0]=>
array(3) {
[0]=>
string(14) "row 0 column 0"
[1]=>
string(14) "row 0 column 1"
[2]=>
string(14) "row 0 column 2"
}
[1]=>
array(3) {
[0]=>
string(14) "row 1 column 0"
[1]=>
string(14) "row 1 column 1"
[2]=>
string(14) "row 1 column 2"
}
[2]=>
array(3) {
[0]=>
string(14) "row 2 column 0"
[1]=>
string(14) "row 2 column 1"
[2]=>
string(14) "row 2 column 2"
}
}
array(4) {
[0]=>
array(3) {
[0]=>
array(3) {
[0]=>
string(10) "item 0.0.0"
[1]=>
string(10) "item 0.0.1"
[2]=>
string(10) "item 0.0.2"
}
[1]=>
array(2) {
[0]=>
string(10) "item 0.1.0"
[1]=>
string(10) "item 0.1.1"
}
[2]=>
array(4) {
[0]=>
string(10) "item 0.2.0"
[1]=>
string(10) "item 0.2.1"
[2]=>
string(10) "item 0.2.2"
[3]=>
string(10) "item 0.2.3"
}
}
[1]=>
array(2) {
[0]=>
array(1) {
[0]=>
string(10) "item 1.0.0"
}
[1]=>
array(1) {
[0]=>
string(10) "item 1.1.0"
}
}
[2]=>
array(1) {
[0]=>
array(2) {
[0]=>
string(10) "item 2.0.0"
[1]=>
string(10) "item 2.0.1"
}
}
[3]=>
array(2) {
[0]=>
array(1) {
[0]=>
string(10) "item 3.0.0"
}
[1]=>
array(2) {
[0]=>
string(10) "item 3.1.0"
[1]=>
string(10) "item 3.1.1"
}
}
}
?>
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, 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.
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 , then explode() will return an array containing string .
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.
explode
07-Jul-2008 07:16
29-Apr-2008 08:16
Here's a nice function to replace multi-regexp searches:
function multiBetween( $source, $search_for, $inc_start_end = false ) {
# Empty Results Array
$results = array();
# Literate through the array
$arr_index = 0;
foreach( $search_for as $index => $find ) {
$result = explode( $find[1], $source );
$result = explode( $find[0], $result[0] );
$results[$arr_index] = ($inc_start_end) ? $find[0] . $result[1] . $find[1] : $result[1];
$arr_index++;
}
return $results;
}
22-Apr-2008 09:02
Beware when you are using explode() to split lines from TSV file.
I have had one file with tab separated values. Since the whole line was one string, everything appeared OK. After exploding long numbers like 9876543210987 were converted to 9.87654E+12, then to string, and this was the value inserted to the database (instead of 9876543210987 as a string). Concatenating with an empty string did not help since the problem appeared inside the explode() function.
Regards,
Pietshaq
28-Mar-2008 07:09
Sample Examples show here:
<?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; // *
?>
19-Mar-2008 01:26
I rewrote explode() so it'll ignore separators that come after a backslash.
<?php
function dexplode($sep,$str){// explode() except $sep's that follow "\" are ignored
$retarr=array();
$thisstr="";
$x=0;
$arrnum=0;
while($x<strlen($str)){
if($str{$x}=="\\"){
if($str{$x+1}=="\\"){
$thisstr.="\\";
$x+=2;
}elseif($str{$x+1}==$sep){
$thisstr.=$sep;
$x+=2;
}else{
$thisstr.="\\";
$x++;
}
}elseif($str{$x}==":"){
$retarr[$arrnum]=$thisstr;
$arrnum++;
$x++;
$thisstr="";
}else{
$thisstr.=$str{$x};
$x++;
}
}
$retarr[$arrnum]=$thisstr;
return $retarr;
}
?>
19-Feb-2008 05:53
Hey a small fix in my code
<?php
/**
* Function abbreviate
* return abbreviate name
* This function is to abbreviate the name. If name is grater than specific length
* then it abbreviate the string
*
*
* Parameters:
* limit - The maximum character count
* string - The name string
*
* Returns:
* string - abbreviated string
*/
function abbreviate($limit, $string, $position=0)
{
$char_limit=$limit;
$string = trim($string);
$str_chunk = explode(' ', $string);
if(strlen($string) > $char_limit) {
if(sizeof($str_chunk) == ($position+1)){
return $string = substr($string, 0, $char_limit);
} else {
$str_chunk[$position] = substr($str_chunk[$position], 0, 1).'.';
return abbreviate($char_limit,implode(' ',$str_chunk), ++$position);
}
} else {
return $string;
}
}
//Usage
$name = 'Abhinav Varshney This Is My Name';
$char_limit=29;
echo abbreviate($char_limit, $name);
// Output::
// A. Varshney This Is My Name
?>
16-Feb-2008 11:35
I wrote this function to shorten long names. Actually database has been designed to hold Full name up to 20 characters but some user name had more than 20 chars.
/**
* Function abbreviate
* return abbreviate name
* This function is to abbreviate the name. If name is grater than specific length
* then it abbreviate the string
*
*
* Parameters:
* limit - The maximum character count
* string - The name string
*
* Returns:
* string - abbreviate string
*/
function abbreviate($limit, $string, $position=0)
{
$char_limit=$limit;
$string = trim($string);
$str_chunk = explode(' ', $string);
if(strlen($string) > $char_limit) {
if(sizeof($str_chunk) == ($position+1)){
return $string = substr($string, 0, $char_limit);
} else {
$str_chunk[$position] = substr($str_chunk[$position], 0, 1).'.';
return abbrivate($char_limit,implode(' ',$str_chunk), ++$position);
}
} else {
return $string;
}
}
//Usage
$name = 'Abhinav Varshney This Is My Name';
$char_limit=29;
echo abbreviate($char_limit, $name);
14-Feb-2008 08:14
This function explodes a string and trims all elements
function explode_and_trim($separator, $text, $trim_chars = false, $limit = false)
{
if ($limit === false)
$arr = explode($separator, $text);
else
$arr = explode($separator, $text, $limit);
$ret = array();
foreach($arr as $e)
{
if ($trim_chars === false)
$ret[] = trim($e);
else
$ret[] = trim($e, $trim_chars);
}
return $ret;
}
13-Dec-2007 01:20
An extension to explode can be explode_assoc. This is reverse of implode_assoc return by Brian and can be found with implode.
<?php
function explode_assoc($glue1, $glue2, $array)
{
$array2=explode($glue2, $array);
foreach($array2 as $val)
{
$pos=strpos($val,$glue1);
$key=substr($val,0,$pos);
$array3[$key] =substr($val,$pos+1,strlen($val));
}
return $array3;
}
//usage:
$str="key1=val1&key2=val2&key3=val3";
$array=explode_assoc('=','&',$str);
print_r($array);
?>
This outputs:
Array
(
[key1] => val1
[key2] => val2
[key3] => val3
)
25-Oct-2007 05:44
We've written a function: explodeTree() that can explode any single-dimensional array into a full blown tree. The function uses a user-specified delimiter found in the keys of the original array to separate nodes and determine hierarchy.
Sample: with 3 lines of code you could have a full directory hierarchy in a multi-dimensional array if you specify the delimiter to be a '/' (slash).
I'm posting a link because the function is being improved by site visitors commenting on the article:
http://kevin.vanzonneveld.net/techblog/article/72/
15-Oct-2007 11:26
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. :)
26-Jul-2007 11:47
This had me for a moment. A quick gotcha, for me, because it was causing some problems in a script of mine.
If you explode an empty string, you'll get an array with one element - an empty string, and not an empty array or string as you may think.
For example:
<?php
$string = "";
$numbers = explode(",", $string); // Array with one element, "".
$string = "1,2,3";
$numbers = explode(",", $string); // Array with three elements
?>
20-Jun-2007 02:28
While trying to use explode() to parse CSV formatted lines output by MS Excel, I found that if cells contained a comma, then explode() would not behave as desired. So I wrote the following function, which obeys the double quote escaping format output by Excel. Note that it is not sophisticated enough to handle delimiters or escapes that consist of more than one character. I also have no idea how this code will perform when subjected to Unicode data. Use at your own risk.
<?php
// splits a string into an array of tokens, delimited by delimiter char
// tokens in input string containing the delimiter character or the literal escape character are surrounded by a pair of escape characteres
// a literal escape character is produced by the escape character appearing twice in sequence
// default delimiter character and escape character are suitable for Excel-exported CSV formatted lines
function splitWithEscape ($str, $delimiterChar = ',', $escapeChar = '"') {
$len = strlen($str);
$tokens = array();
$i = 0;
$inEscapeSeq = false;
$currToken = '';
while ($i < $len) {
$c = substr($str, $i, 1);
if ($inEscapeSeq) {
if ($c == $escapeChar) {
// lookahead to see if next character is also an escape char
if ($i == ($len - 1)) {
// c is last char, so must be end of escape sequence
$inEscapeSeq = false;
} else if (substr($str, $i + 1, 1) == $escapeChar) {
// append literal escape char
$currToken .= $escapeChar;
$i++;
} else {
// end of escape sequence
$inEscapeSeq = false;
}
} else {
$currToken .= $c;
}
} else {
if ($c == $delimiterChar) {
// end of token, flush it
array_push($tokens, $currToken);
$currToken = '';
} else if ($c == $escapeChar) {
// begin escape sequence
$inEscapeSeq = true;
} else {
$currToken .= $c;
}
}
$i++;
}
// flush the last token
array_push($tokens, $currToken);
return $tokens;
}
?>
25-May-2007 04:49
@ tobylewis
No, it should not return a null array! The description clearly states: If delimiter contains a value that is not contained in string, then explode() will return an array containing string.
So it returns an array containing the original (empty) string.
Wouldn't you test for an invalid email address before trying to mail to it anyway? :S
25-May-2007 11:01
Watch out for this gottcha. Consider:
$arr = explode("/", "");
This should return a null array (ie count($arr) == 0).
Array
(
)
However, explode will instead return an array of one item which is a null string.
Array
(
[0] =>
)
There is some logic to the way this works but consider the following:
$addressees = "email@domain1.com, email@domain2.com";
$arr = explode(",", $addressees);
foreach($arr AS $to) mail ($to, $subject, $message);
with two items in the list it would sent two separate emails, with one it would sent one email message but with $addressees = "" it will still attempt to send one message that will fail because instead of returning an empty array explode returns an array with an empty item.
17-May-2007 05:45
@ JJ Rock, jason dot minett:
Here's an easy way around that:
<?php
$str = '^one^two^three^';
//Use trim() to remove extra delimiters
$arr = explode ('^', trim($str, '^'));
?>
27-Apr-2007 01:02
Just a quick note to compliment jason dot minett's comment a few down:
It's obvious that this works the opposite way as well:
<?php
$str = "^one^two^three";
$arr = explode ("^", $str);
?>
results in an empty value in $arr[0].
26-Apr-2007 11:08
<?php
// returns a string where $variables are replaced with their global value if available; removes all extra whitespaces
function evaluateString($string) {
if ($string) { // check for value
$array = explode(' ', $string); // split into parts
foreach ($array as $word) { // each part
if ($word[0] == '$') { // is part a variable
if ($word = substr($word, 1)) { // get variable name
global ${$word}; // retrieve global value
$html .= ${$word}; // add value to string
} // end variable name check
} else { // not a variable
$html .= $word; // add word to string
} // end variable check
$html .= ' '; // add space between words
} // end part loop
} // end string check
return trim($html); // trims final space from end
} // end evaluateString
?>
23-Apr-2007 03:43
of cause i ment the limit with my previouse post
@admin: wold u please change every "delimiter" in that post to "limit" and delete this note. thx.
22-Apr-2007 05:30
some more notes on the delimiter:
if the delimiter is 0, explode will return an array with one element containig the hole string (same as if the delimiter was 1).
if a negative delimiter is bigger or equal to the number of components, an empty array is returned.
<?php
print_r( explode( "|", "one|two|three|four", 0) );
print_r( explode( "|", "one|two|three|four", 1) );
?>
both print:
Array
(
[0] => one|two|tree|four
)
<?php
print_r( explode( "|", "one|two|three|four", -4) );
print_r( explode( "|", "one|two|three|four", -5) );
?>
both print:
Array
(
)
01-Mar-2007 05:09
A quick gotcha that had me head scratching for a while....
If the delimiter occurs right at the end of the string there will be an extra array element (an empty string):
<?php
$str = "aaa^elephant^chocolate^albatross^";
$arr = explode ("^", $str);
echo ("Array length: ".count($arr));
?>
---------------------------------
Array length: 5
27-Feb-2007 08:59
insensitive case explode function:
<?php
function iExplode($Delimiter, $String, $Limit = '')
{
$Explode = array();
$LastIni = 0;
$Count = 1;
if (is_numeric($Limit) == false)
$Limit = '';
while ( false !== ( $Ini = stripos($String, $Delimiter, $LastIni) ) && ($Count < $Limit || $Limit == ''))
{
$Explode[] = substr($String, $LastIni, $Ini-$LastIni);
$LastIni = $Ini+strlen($Delimiter);
$Count++;
}
$Explode[] = substr($String, $LastIni);
return $Explode;
}
?>
17-Dec-2006 06:28
A 'between' function that we've all been waiting for. I am not savvy with regex so I resorted to explode();
<?php
function between($beg, $end, $str) {
$a = explode($beg, $str, 2);
$b = explode($end, $a[1]);
return $beg . $b[0] . $end;
}
echo between('<a>', '</a>', 'fsdfsdfsd<a>fsdfsd<a><a></a>sdfsdfsdf')
//<a>fsdfsd<a><a></a>
?>
10-Dec-2006 04:49
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));
?>
20-Oct-2006 08:50
// simple function to remove words if more than max allowed words or add a charcter once less than min
// 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;
}
13-Mar-2006 07:20
If you want to split a price (float) into pounds and pence.
or dollors and cents etc etc.
$price = "6.20";
$split = explode(".", $price);
$pound = $split[0]; // piece1
$pence = $split[1]; // piece2
echo "£ $pound . $pence\n";
01-Dec-2004 01:50
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 05:01
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");
