PHP Doku:: Teilt einen String anhand einer Zeichenkette - function.explode.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchFunktionsreferenzTextverarbeitungZeichenkettenString-Funktionenexplode

Ein Service von Reinhard Neidl - Webprogrammierung.

String-Funktionen

<<echo

fprintf>>

explode

(PHP 4, PHP 5)

explodeTeilt einen String anhand einer Zeichenkette

Beschreibung

array explode ( string $delimiter , string $string [, int $limit ] )

Gibt ein Array aus Strings zurück, die jeweils Teil von string sind. Die Abtrennung erfolgt dabei an der mit delimiter angegebenen Zeichenkette.

Parameter-Liste

delimiter

Die Begrenzungszeichenkette.

string

Die Eingabezeichenkette.

limit

Ist der Parameter limit angegeben und positiv, enthält das zurückgegebene Array maximal limit Elemente, wobei das letzte Element den Rest von string beinhaltet.

Ist der Parameter limit negativ, werden alle Teilstrings bis auf die letzten -limit Teile zurückgegeben.

Wenn der Parameter limit gleich null ist, wird er wie 1 behandelt.

Obgleich implode() aus historischen Gründen die Parameter in anderer Reihenfolge akzeptiert, verarbeitet explode() ausschließlich die hier angegebene Reihenfolge. Stellen Sie daher sicher, dass Sie den Parameter delimiter vor dem Parameter string notieren.

Rückgabewerte

Ist delimiter ein leerer String (""), so gibt explode() FALSE zurück. Enthält delimiter einen Wert, der nicht in string vorkommt und wird ein negativer Wert für limit verwendet, wird ein leeres Array zurückgegeben. Für alle anderen Werte von limit wird ein Array zurückgegeben, das den string als einziges Element enthält.

Changelog

Version Beschreibung
5.1.0 Die Unterstützung für negative limit-Werte wurde hinzugefügt.
4.0.1 Der Parameter limit wurde hinzugefügt.

Beispiele

Beispiel #1 explode()-Beispiele

<?php
// Beispiel 1
$pizza  "Teil1 Teil2 Teil3 Teil4 Teil5 Teil6";
$teile explode(" "$pizza);
echo 
$teile[0]; // Teil1
echo $teile[1]; // Teil2

// Beispiel 2
$data "foo:*:1023:1000::/home/foo:/bin/sh";
list(
$user$pass$uid$gid$gecos$home$shell) = explode(":"$data);
echo 
$user// foo
echo $pass// *

?>

Beispiel #2 limit-Parameterbeispiele

<?php
$str 
'eins|zwei|drei|vier';

// positiver Wert in "limit"
print_r(explode('|'$str2));

// negative Wert in "limit" (ab PHP 5.1)
print_r(explode('|'$str, -1));
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Array
(
    [0] => eins
    [1] => zwei|drei|vier
)
Array
(
    [0] => eins
    [1] => zwei
    [2] => drei
)

Anmerkungen

Hinweis: Diese Funktion ist binary safe.

Siehe auch

  • preg_split() - Zerlegt eine Zeichenkette anhand eines regulären Ausdrucks
  • str_split() - Konvertiert einen String in ein Array
  • str_word_count() - Gibt Informationen über in einem String verwendete Worte zurück
  • strtok() - Zerlegt einen String
  • implode() - Verbindet Array-Elemente zu einem String


39 BenutzerBeiträge:
- Beiträge aktualisieren...
eye_syah88 at yahoo dot com
30.05.2011 9:32
a simple one line method to explode & trim whitespaces from the exploded elements

array_map('trim',explode(",",$str));

example:

$str="one  ,two  ,       three  ,  four    ";
print_r(array_map('trim',explode(",",$str)));

Output:

Array ( [0] => one [1] => two [2] => three [3] => four )
Rijk van Wel
17.05.2011 17:05
Here's another one of those functions that allow you to work with an escaped delimiter. It works by internally url-encoding the escaped delimiters before calling explode(). So if your delimiter is a %, you should use another encoding function ;)

<?php
function explode_escaped( $delimiter, $string ) {
   
$string = str_replace( '\\' . $delimiter, urlencode( $delimiter ), $string );
    return
array_map( 'urldecode', explode( $delimiter, $string ) );
}
?>
bernard.schenk [at] bordet.be
17.05.2011 11:53
Nifty multiple explode function:

<?php
function multipleExplode($delimiters = array(), $string = ''){

   
$mainDelim=$delimiters[count($delimiters)-1]; // dernier
   
   
array_pop($delimiters);
   
    foreach(
$delimiters as $delimiter){
   
       
$string= str_replace($delimiter, $mainDelim, $string);
   
    }

   
$result= explode($mainDelim, $string);
    return
$result;

}
?>
alexander at textalk dot se
12.04.2011 9:27
If the string begins or ends with the delimiter:

<?php

$path
= '/one/two/three/';
$folderNames = explode('/', $path);
print_r($folderNames);

?>

Will give:

Array
(
    [0] =>
    [1] => one
    [2] => two
    [3] => three
    [4] =>
)
lm at ms dot net
23.03.2011 12:58
while explode() and implode() are counterparts, note that it does NOT work for an empty delimiter!

solution: use str_split($str) instead of explode('', $str)

example:
<?php
$str1
= 'abc';
var_dump($str1);

$str2 = implode(',' , explode(',' , $str1)); // OK (explode with non-empty delimiter)
var_dump($str2);

$str3 = implode('' , str_split($str1));      // OK (str_split)
var_dump($str3);

$str4 = implode('' , explode('' , $str1));   // ERROR! (explode with empty delimiter)
var_dump($str4);
?>

returns:
string 'abc' (length=3)
string 'abc' (length=3)
string 'abc' (length=3)
Warning: explode() [function.explode]: Empty delimiter.
Warning: implode() [function.implode]: Bad arguments.
null
Kamba Jeno
19.03.2011 14:47
if u cannot use the original function explode, or your version is less than 4.0.1 you can use this example  whith optional limit argument.

<?php
function exploding($separator,$string,$limit=NULL){
$returnarray = array();
$increment = 0;
$length = strlen($string);
$limit_negative=($limit < 0);

    for(
$i = 0; $i < $length;$i++){
       
$current = substr($string,$i,1);
        
//main explode function
           
if($separator == $current){
           
$increment++;
            }
            elseif(
$separator == ""){   
            @
$returnarray[$increment].=$current;
           
$increment++;   
            }
            else{
            @
$returnarray[$increment].=$current;
            }
       
//if limit is positive
       
if(isset($limit) && $limit == $increment){
        break;
        }
       
    }
   
//if limit is negative
   
if($limit_negative){
        for(
$i = 0; $i > $limit;$i--){
          
array_pop($returnarray);
           }
   
   
    }
return
$returnarray;
}

//Test
$something = "Kamba.jeno.attila";

$result = exploding(".",$something)
/*returns
array(3) {
[0]=> string(5) "Kamba"
[1]=> string(4) "Jeno"
[2]=> string(6) "Attila" }
*/

$result2 = exploding(".",$something,1)
/*returns
array(1) {
[0]=> string(5) "Kamba" }
*/

$result3 = exploding(".",$something,-1)
/*returns
array(2) {
[0]=> string(5) "Kamba"
[1]=> string(4) "Jeno" }
*/
?>
Aram Kocharyan
28.02.2011 4:04
Here is a function to explode a comma separated string and trim the elements of any whitespace that may come before or after the comma, and will also trim whitespace from the front and end of the string, as well as allow you to specify a delimiter yourself.

<?php

/* Performs explode() on a string with the given delimiter and trims all whitespace for the elements */
function explode_trim($str, $delimiter = ',') {
    if (
is_string($delimiter) ) {
       
$str = trim(preg_replace('|\\s*(?:' . preg_quote($delimiter) . ')\\s*|', $delimiter, $str));
        return
explode($delimiter, $str);
    }
    return
$str;
}

// Test
$str = '    mouse ,cat , dog  ,  human    ';
$array = explode_trim($str);
print_r($array);

?>

This will output:
(
    [0] => mouse
    [1] => cat
    [2] => dog
    [3] => human
)
jehoshua02 at gmail dot com
23.02.2011 8:37
If you are looking for a simpler multi-explode that returns a flat array, use a regular expression to standardize all delimiters before exploding.

<?php

// function to explode on multiple delimiters
function multi_explode($pattern, $string, $standardDelimiter = ':')
{
   
// replace delimiters with standard delimiter, also removing redundant delimiters
   
$string = preg_replace(array($pattern, "/{$standardDelimiter}+/s"), $standardDelimiter, $string);

   
// return the results of explode
   
return explode($standardDelimiter, $string);
}

// test

    // set up variables
   
$string = "zero  one | two :three/ four\ five:: six|| seven eight nine\n ten \televen twelve thirteen fourteen fifteen";
   
$pattern = '/[:\|\\\\\/\s]/'// colon (:), pipe (escaped '\|'), slashes (escaped '\\\\' and '\/'), white space (\s)

    // call function
   
$result = multi_explode($pattern, $string);
   
   
// display results
   
var_dump($result);

?>

Output:

array
  0 => string 'zero' (length=4)
  1 => string 'one' (length=3)
  2 => string 'two' (length=3)
  3 => string 'three' (length=5)
  4 => string 'four' (length=4)
  5 => string 'five' (length=4)
  6 => string 'six' (length=3)
  7 => string 'seven' (length=5)
  8 => string 'eight' (length=5)
  9 => string 'nine' (length=4)
  10 => string 'ten' (length=3)
  11 => string 'eleven' (length=6)
  12 => string 'twelve' (length=6)
  13 => string 'thirteen' (length=8)
  14 => string 'fourteen' (length=8)
  15 => string 'fifteen' (length=7)

See:
http://www.php.net/manual/en/book.pcre.php
dhz
30.12.2010 18:21
A one-liner to extract a portion of a string, starting from the END of the string....
<?php
$extracted_string
= implode('.', array_slice(explode('.', $original_string), -2));
?>
jamestrowbridge at gmail dot com
19.12.2010 21:50
FYI, use double quotes for the separator parameter:

<?php
$string
= "Hello\nHello\nHello";
$arr = explode('\n',$string);//Using single quotes
print_r($arr);
/*
Returns:
Array
(
    [0] => Hello
Hello
Hello
)
*/
?>
Is different than:
<?php
$string
= "Hello\nHello\nHello";
$arr = explode("\n",$string);//Using double quotes
print_r($arr);
/*
Returns:
Array
(
    [0] => Hello
    [1] => Hello
    [2] => Hello
)
*/
?>
xananax at yelostudio dot com
10.11.2010 15:18
I needed a way to explode an array, just like one would explode a string, and could not find anything on the net.
Maybe this can be made more efficient, but it fits my purpose. Contributions and comments welcome.
<?php
   
/**
     * Allows to explode an array into multiple arrays on a set delimiter.
     * Delimiter Can be set either by key, or by value, or by both (in which case,
     * both key and value must be strictly equal to values provided).
     * Note that numeric indexes don't work since the original array is reduced
     * at each loop (thus making numerical indexes useless).
     * @param array $array the array to explode
     * @param mixed $key the key to check
     * @param mixed $value the value to check
     * @param int $limit You can limit the number of parts with this. If set to 0, limit is infinite
     * @param boolean $removeDelimiter if set to TRUE, removes the delimiter key from the returned arrays
     * @return array|boolean an array of as many parts as needed, or FALSE on error.
     */
   
function array_explode(array $array, $key=NULL, $value=NULL, $limit=0, $removeDelimiter=TRUE){
        if(
$key===NULL && $value===NULL){return FALSE;}
       
$parts = array();
       
$delimiter = NULL;
       
$partsN = 0;
        while(
$v = current($array)){
           
$k = key($array);
            if(
                ((
$key!==NULL && $value!==NULL) && ($k===$key && $v===$value)) ||
                (
$key!==NULL && $value===NULL && $k===$key) ||
                (
$value!==NULL && $key===NULL && $v===$value)
            ){
               
$delimiter = TRUE;
                if(
$removeDelimiter){array_shift($array);}
               
$partsN++;
                if(
$partsN===$limit){$parts[$partsN] = $array;return $parts;}
            }
           
$parts[$partsN][] = array_shift($array);
        }
        if(
$delimiter){
            return
$parts;
        }
        return
FALSE;
    }
?>
mvpetrovich
10.09.2010 2:35
In using explode, with the list command, you will get errors if the number of variables is larger than the produced array by explode.

For example:

<?php
$str
= 'aa|bb|cc';
list(
$one, $two, $three, $four) = explode('|', $str);
?>

To solve these cases, where you would like to assign empty strings to the extra variables (and eliminate errors), append a delimiter string to the string as follows.

<?php
$str
= 'aa|bb|cc';
list(
$one, $two, $three, $four) = explode('|', $str . '|||');
?>

This way, the list variables will always be assigned.
tiago dot dias at flow-me dot com
9.09.2010 12:40
Beaware splitting empty strings.

<?php
$str
= "";
$res = explode(",", $str);
print_r($res);
?>

If you split an empty string, you get back a one-element array with 0 as the key and an empty string for the value.

Array
(
    [0] =>
)

To solve this, just use array_filter() without callback. Quoting manual page "If the callback function is not supplied, array_filter() will remove all the entries of input that are equal to FALSE.".

<?php
$str
= "";
$res = array_filter(explode(",", $str));
print_r($res);
?>

Array
(
)
Cody G.
8.08.2010 15:41
I'm sure you guys get just a bit frustrated at times when you need a fraction of a very simple string and you use "explode()", but then you have to define a whole extra variable. (That is because you need to store a function-returned array in a variable before you can extract a value).

If you're extracting the last half, or third, of a string, there's an easy inline workaround. Check this:

<?php
 $mystr
= "separated-text";
 print(
str_replace("-","",strstr("-",$mystr)));
 
//Returns "text"
?>

If the separator (dash) can be left in, you don't even need the "str_replace()" function.

Lets try this with 3 fractions:

<?php
 $mystr
= "separated-text-again";
 
//Comment submission wouldn't let me
 // combine this into one statement.
 // That's okay, it's more readable.
 
$split1 = str_replace("-","",strstr("-",$mystr));
 print(
str_replace("-","",strstr("-",$split1)));
 
//Returns "again"
?>

Anything more than 3 fractions gets really confusing, in that case you should use "explode()".

Hope this helps!
~Cody G.
m0gr14 at gmail dot com
31.07.2010 16:02
Here's a function for "multi" exploding a string.

<?php
//the function
//Param 1 has to be an Array
//Param 2 has to be a String
function multiexplode ($delimiters,$string) {
   
$ary = explode($delimiters[0],$string);
   
array_shift($delimiters);
    if(
$delimiters != NULL) {
        foreach(
$ary as $key => $val) {
            
$ary[$key] = multiexplode($delimiters, $val);
        }
    }
    return 
$ary;
}

// Example of use
$string = "1-2-3|4-5|6:7-8-9-0|1,2:3-4|5";
$delimiters = Array(",",":","|","-");

$res = multiexplode($delimiters,$string);
echo
'<pre>';
print_r($res);
echo
'</pre>';

//returns
/*
Array
(
    [0] => Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [0] => 1
                            [1] => 2
                            [2] => 3
                        )

                    [1] => Array
                        (
                            [0] => 4
                            [1] => 5
                        )

                    [2] => Array
                        (
                            [0] => 6
                        )

                )

            [1] => Array
                (
                    [0] => Array
                        (
                            [0] => 7
                            [1] => 8
                            [2] => 9
                            [3] => 0
                        )

                    [1] => Array
                        (
                            [0] => 1
                        )

                )

        )

    [1] => Array
        (
            [0] => Array
                (
                    [0] => Array
                        (
                            [0] => 2
                        )

                )

            [1] => Array
                (
                    [0] => Array
                        (
                            [0] => 3
                            [1] => 4
                        )

                    [1] => Array
                        (
                            [0] => 5
                        )

                )

        )

)
*/
?>
info at noextratime dot com
4.07.2010 10:09
Here is a function for "double" exploding a string, like in the case of a flattened multi-dimensional array.
<?php

function doubleExplode ($del1, $del2, $array){
   
$array1 = explode("$del1", $array);
foreach(
$array1 as $key=>$value){
$array2 = explode("$del2", $value);
foreach(
$array2 as $key2=>$value2){
$array3[] = $value2
}
}
   
$afinal = array();
for (
$i = 0; $i <= count($array3); $i += 2) {
    if(
$array3[$i]!=""){
   
$afinal[trim($array3[$i])] = trim($array3[$i+1]);
    }
}
return
$afinal;
}
$proddetails = 'Size=Large, Color=Black';
$test = doubleExplode(',', '=', $proddetails);
print_r($test);
?>

/*
Array
(
    [Size] => Large
    [Color] => Black
)
*/
jessebusman at gmail dot com
27.05.2010 21:45
Sometimes you need to explode a string by different delimiters. In that case you can use this function:

<?php
print_r
(explodeX(Array(".","!"," ","?",";"),"This.sentence?contains wrong;characters"));
// Returns:
// Array("This","sentence","contains","wrong","characters")

function explodeX($delimiters,$string)
{
   
$return_array = Array($string); // The array to return
   
$d_count = 0;
    while (isset(
$delimiters[$d_count])) // Loop to loop through all delimiters
   
{
       
$new_return_array = Array();
        foreach(
$return_array as $el_to_split) // Explode all returned elements by the next delimiter
       
{
           
$put_in_new_return_array = explode($delimiters[$d_count],$el_to_split);
            foreach(
$put_in_new_return_array as $substr) // Put all the exploded elements in array to return
           
{
               
$new_return_array[] = $substr;
            }
        }
       
$return_array = $new_return_array; // Replace the previous return array by the next version
       
$d_count++;
    }
    return
$return_array; // Return the exploded elements
}
?>
Onur Nizam onur dot nizam at yahoo dot com
16.05.2010 9:27
The regular expression parameters such as \n or \t can be used as well as other strings as the delimeter which can be used to parse any given text files or downloaded web pages to read line by line.

An example may be considered as, name surname and phone numbers are written into a text file line by line and columns are seperated by tabs, can be exploded and read easily through the return and tab characters. After storing them in the array they can be manipulated or displayed in any other formats.

<?php
// Explode text file and store each row of the file into the array elements
function explodeRows($data) {
 
$rowsArr = explode("\n", $data);
  return
$rowsArr;
}

// Explode the columns according to tabs
function explodeTabs($singleLine) {
 
$tabsArr = explode("\t", $singleLine);
  return
$tabsArr;
}

// Open the text file and get the content
$filename = "phonebook.txt";
$handle   = fopen($filename, 'r');
$data     = fread($handle, filesize($filename));
$rowsArr  = explodeRows($data);

// Display content which is exploded by regular expression parameters \n and \t
for($i=0;$i<count($rowsArr);$i++) {
 
$lineDetails = explodeTabs($rowsArr[$i]);
    echo
"<br>Name : " . $lineDetails[0];
    echo
"<br>Surname : " . $lineDetails[1];
    echo
"<br>Tel Number : " . $lineDetails[2];
    echo
"<br><br>";
}

/*
phonebook.txt text file can be something like this;
name1    sname1    +905429998877
name2    sname2    +905429998876
name3    sname3    +905429998875

The output will be as follows;
Name : name1
Surname : sname1
Tel Number : +905429998877

Name : name2
Surname : sname2
Tel Number : +905429998876

Name : name3
Surname : sname3
Tel Number : +905429998875
*/

?>
drieick at hotmail dot com
22.04.2010 5:34
When explode is given an empty $string, it'll return an array with a single empty element.

<?php

# returns Array([0] => );
print_r(explode(',', ''));

?>

This is not a bug, but it can be pretty tricky (especially with callbacks that expect a certain type of array). So, be sure to check your arrays. It's not a bug, because there's nothing to split.
locoluis at gmail dot com
8.04.2010 18:02
That with all stateful encodings that use bytes between 0x00 and 0x7f for something other than, say, encoding ASCII characters. Including GBK, BIG5, Shift-JIS etc.

explode and other such PHP functions work on bytes, not characters.

What you do is to convert the string to UTF-8 using iconv(), then explode, then go back to GBK.
gxd305 at gmail dot com
17.11.2009 2:47
when the encoding of $string  is 'GBK' and $delimiter is '|' , the return value may be wrong.
for example:

<?php
$result
= explode("|", "滕华弢|海青");
var_dump($result);
?>

and the result will be:
array (
  0 => '滕华,
  1 => '',
  2 => '海青',
)

bcz "弢" 's GBK is '0x8f7c'. and "|" 's ASCII is '0x7c'.

So, all GBK-encoding characters include '7c' will lead to the error result.
nick dot brown at free dot fr
15.10.2009 0:47
My application was running out of memory (my hosting company limits PHP to 32MB).  I have a string containing between 100 and 20000 triplets, separated by a space, with each triplet consisting of three double-precision numbers, separated by commas.  Total size of the biggest string, with 20000 triplets, is about 1MB.

The application needs to split the string into triplets, then split the triplet into numbers.  In C, this would take up about 480K (20000 times 3 x 8 bytes) for the final array.  The intermediate array of strings shouldn't be much bigger than the long string itself (1MB).  And I expect some overhead from PHP, say 300% to allow for indexes etc.

Well, PHP5 manages to run out of memory *at the first stage* (exploding the string on the space character).  I'm expecting to get an array of 20000 strings, but it needs more than 32MB to store it.  Amazing.

The workaround was easy and had the bonus of producing faster code (I compared it on a 10000 triplet string).  Since in any case I had to split up the numeric triplets afterwards, I decided to use preg_match_all() on the original string.  Despite the fact that the resulting "matches" array contains more data per element than the result of explode() - because it stores the matched triplet, plus its component numbers - it takes up far less memory.

Moral: be careful when using explode() on big strings, as it can also explode your memory usage.
Jrg Wagner
12.10.2009 23:28
Here is a very concise example for a quote aware explode - substrings in quotes (or another definable enclosure char) are not exploded.
An additional parameter allows to determine whether the enclosure chars should be preserved within the resulting array elements. Please note that as of PHP 5.3 the str_getcsv function offers a built-in way to do this!

<?php
function csv_explode($delim=',', $str, $enclose='"', $preserve=false){
 
$resArr = array();
 
$n = 0;
 
$expEncArr = explode($enclose, $str);
  foreach(
$expEncArr as $EncItem){
    if(
$n++%2){
     
array_push($resArr, array_pop($resArr) . ($preserve?$enclose:'') . $EncItem.($preserve?$enclose:''));
    }else{
     
$expDelArr = explode($delim, $EncItem);
     
array_push($resArr, array_pop($resArr) . array_shift($expDelArr));
     
$resArr = array_merge($resArr, $expDelArr);
    }
  }
  return
$resArr;
}
?>
Anonymous
29.09.2009 0:20
Note to the previous example: we can do the whole string->array conversion using explode() exclusively.

<?php
   
// converts pure string into a trimmed keyed array
   
function string_2_array( $string, $delimiter = ',', $kv = '=>')
    {
        if (
$element = explode( $delimiter, $string ))
        {
           
// create parts
           
foreach ( $element as $key_value )
            {
               
// key -> value pair or single value
               
$atom = explode( $kv, $key_value );

                if(
trim($atom[1]) )
                {
                 
$key_arr[trim($atom[0])] = trim($atom[1]);
                }
                else
                {
                   
$key_arr[] = trim($atom[0]);
                }
            }
        }
        else
        {
           
$key_arr = false;
        }

        return
$key_arr;
    }
?>
Anonymous
3.09.2009 4:18
<?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));
?>

Array
(
  [a] => 1
  [b] => 23
  [0] => $a
  [c] => 45%
  [1] => true
  [d] => ab c
)
Anonymous
11.08.2009 7:55
If you are exploding string literals in your code that have a dollar sign ($) in it, be sure to use single-quotes instead of double-quotes, since php will not spare any chance to interpret the variable-friendly characters after the dollar signs as variables, leading to unintended consequences, the most typical being missing characters.

<?php
$doubleAr
= explode(" ", "The $quick brown fox");
$singleAr = explode(" ", 'The $quick brown fox');
echo
$doubleAr[1]; // prints "";
echo $singleAr[1]; // prints "$quick";
?>
vzverev at nm dot ru
24.07.2009 16:33
If you are going to use foreach after explode(), call reset() before foreach:
<?php
$arr
= explode("\n", 'test \n test2 \n test3');
reset($arr);
foreach(
$arr as $line)
{
/* do something */ ; }
?>
marcus at synchromedia dot co dot uk
15.06.2009 15:50
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.
SR
21.04.2009 16:50
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.
Michael
19.04.2009 11:29
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');
 }

?>
Navi
31.03.2009 14:03
<?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
)
adrian at bilsoftware dot com
23.02.2009 23:40
<?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
)
Elad Elrom
5.12.2008 6:02
<?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;
}
?>
Nobody
17.11.2008 2:38
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 :)
shaun
29.08.2008 21:24
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.)
pinkgothic at gmail dot com
15.10.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. :)
seventoes at gmail dot com
10.12.2006 4: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));
?>
djogo_curl at yahoo
1.12.2004 13: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.
coroa at cosmo-genics dot com
16.11.2003 17: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");



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)