文字

explode

(PHP 4, PHP 5)

explode使用一个字符串分割另一个字符串

说明

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

此函数返回由字符串组成的数组,每个元素都是 string 的一个子串,它们被字符串 delimiter 作为边界点分割出来。

参数

delimiter

边界上的分隔字符。

string

输入的字符串。

limit

如果设置了 limit 参数并且是正数,则返回的数组包含最多 limit 个元素,而最后那个元素将包含 string 的剩余部分。

如果 limit 参数是负数,则返回除了最后的 -limit 个元素外的所有元素。

如果 limit 是 0,则会被当做 1。

由于历史原因,虽然 implode() 可以接收两种参数顺序,但是 explode() 不行。你必须保证 separator 参数在 string 参数之前才行。

返回值

此函数返回由字符串组成的 array ,每个元素都是 string 的一个子串,它们被字符串 delimiter 作为边界点分割出来。

如果 delimiter 为空字符串(""), explode() 将返回 FALSE 。 如果 delimiter 所包含的值在 string 中找不到,并且使用了负数的 limit , 那么会返回空的 array , 否则返回包含 string 单个元素的数组。

更新日志

版本 说明
5.1.0 支持负数的 limit
4.0.1 增加了参数 limit

范例

Example #1 explode() 例子

<?php
// 示例 1
$pizza   "piece1 piece2 piece3 piece4 piece5 piece6" ;
$pieces  explode ( " " $pizza );
echo 
$pieces [ 0 ];  // piece1
echo  $pieces [ 1 ];  // piece2

// 示例 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 explode() return examples

<?php

$input1  "hello" ;
$input2  "hello,there" ;
var_dump explode ',' $input1  ) );
var_dump explode ',' $input2  ) );

?>

以上例程会输出:

array(1)
(
    [0] => string(5) "hello"
)
array(2)
(
    [0] => string(5) "hello"
    [1] => string(5) "there"
)

Example #3 limit 参数的例子

<?php
$str 
'one|two|three|four' ;

// 正数的 limit
print_r ( explode ( '|' $str 2 ));

// 负数的 limit(自 PHP 5.1 起)
print_r ( explode ( '|' $str , - 1 ));
?>

以上例程会输出:

Array
(
    [0] => one
    [1] => two|three|four
)
Array
(
    [0] => one
    [1] => two
    [2] => three
)

注释

Note: 此函数可安全用于二进制对象。

参见

  • preg_split() - 通过一个正则表达式分隔字符串
  • str_split() - 将字符串转换为数组
  • mb_split() - 使用正则表达式分割多字节字符串
  • str_word_count() - 返回字符串中单词的使用情况
  • strtok() - 标记分割字符串
  • implode() - 将一个一维数组的值转化为字符串

用户评论:

[#1] kenorb at niepodam dot pl [2015-10-20 21:48:06]

If you need to split by multiple characters, use preg_split() instead:

    $new_string = preg_split("/[&=:]/", $string);

[#2] Marek [2015-09-14 16:13:27]

The default $limit is NULL, but actually passing NULL as the $limit parameter instead of omitting it will yield different results:
<?php
    explode
('-''A-B-C'null);  => 'A-B-C', ];
    
explode('-''A-B-C');        => 'A'=> 'B'=> 'C', ];
?>

[#3] wado [2014-11-23 02:17:37]

It should be said that when an empty delimiter is passed to explode, the function not only will return false but will also emit a warning.

<?php
var_dump
explode('','asdasd') );


?>

[#4] david dot drakulovski at gmail dot com [2014-02-25 10:58:17]

I made this code for some useful filtering texts with lot of gibberish. Example provided:

<?php
$text 
"There are;many|variations of:passages of Lorem Ipsum available,but the/majority have\"suffered|alteration in some form,by injected humour,or randomised words which don't look even.slightly:believable./";

$delimiter = array(" ",",",".","'","\"","|","\\","/",";",":");
$replace str_replace($delimiter$delimiter[0], $text);
$explode explode($delimiter[0], $replace);

echo 
'<pre>';
print_r($explode);
echo 
'</pre>';
// replaces many symbols in text, then explodes it
?>


This will output the following:
Array
(
    [0] => There
    [1] => are
    [2] => many
    [3] => variations
    [4] => of
    [5] => passages
    [6] => of
    [7] => Lorem
    [8] => Ipsum
    [9] => available
    [10] => but
    [11] => the
    [12] => majority
    [13] => have
    [14] => suffered
    [15] => alteration
    [16] => in
    [17] => some
    [18] => form
    [19] => by
    [20] => injected
    [21] => humour
    [22] => or
    [23] => randomised
    [24] => words
    [25] => which
    [26] => don
    [27] => t
    [28] => look
    [29] => even
    [30] => slightly
    [31] => believable
    [32] => 
    [33] => 
)

[#5] artaxerxes2 at iname dot com [2014-01-31 16:29:58]

Note that using explode() on an empty string returns a non-empty array.

So the code:
<?php
  print_r
(explode("|","");
?>

returns:
Array
(
    [0] => 
)

If you need to return an empty array in the case of an empty string, you must call array_diff() after the explode:
<?php
  print_r
(array_diff(explode("|",""),array("")));
?>

returns:
Array
(
)

This is useful in case your use of MySQL's group_concat() returns an empty string for just some records but you want to convert them all to arrays that actually reflect what group_concat() gave you

[#6] crog at gustavus dot edu [2013-08-01 19:52:55]

Note that while the documentation states the "If limit is set and positive," passing a null-value will still result in triggering the "limit is zero" case (as of PHP 5.4.17).

When passing through values (such as using explode to implement an interface method), you'll need to explicitly check that the limit has been set:

<?php
  
public function split($string$delimiter$limit null)
  {
    return isset(
$limit) ? explode($delimiter$string$limit) : explode($delimiter$string);
  }
?>


Failing to check $limit and simply passing through a null-value will return the same value as if $limit were 0 or 1. To clarify, all of the following will return the same value:

<?php
explode
($string$delimiternull);
explode($string$delimiter0);
explode($string$delimiter1);
?>

[#7] Hayley Watson [2013-03-12 21:13:48]

The comments to use array_filter() without a callback to remove empty strings from explode's results miss the fact that array_filter will remove all elements that, to quote the manual,  "are equal to FALSE".

This includes, in particular, the string "0", which is NOT an empty string.

If you really want to filter out empty strings, use the defining feature of the empty string that it is the only string that has a length of 0. So:
<?php
array_filter
(explode(':'"1:2::3:0:4"), 'strlen');
?>

[#8] m.reesinck [2013-02-18 12:59:23]

I needed a multiexplode which didn't replace my delimiters for 1 other delimiter. Because I couldn't find one in the examples I made one.

delimiter array:
array('/RTRN/','/BUSP/','/BENM/','/ORDP/','/CSID/', '/MARF/','/EREF/', '/PREF/','/REMI/','/ID/','/PURP/', '/ULTB/','/ULTD/');

input string: /RTRN/MS03//BENM/NL50INGB00012345/BUSP/Europese Incasso/eenmalig/67/INGBNL2A/ING Bank N.V. inzake WeB///CSID/NL32ZZZ999999991234//MARF/EV45451//EREF/EV45451 REP170112T1106//REMI///EV45451REP170112T1106/

output:
array(
[/RTRN/] => MS03/
[/BENM/] => NL50INGB00012345
[/BUSP/] => Europese Incasso/eenmalig/67/INGBNL2A/ING Bank N.V. inzake WeB//
[/CSID/] => NL32ZZZ999999991234/
[/MARF/] => EV45451/
[/EREF/] => EV45451REP170112T1106/
[/REMI/] => //EV45451REP170112T1106/
[/ORDP/] => 
[/PREF/] => 
[/ID/] => 
[/PURP/] => 
[/ULTB/] => 
[/ULTD/] =>
)

<?php
function multiexplode($delimiters,$string) {
            
        
$arrOccurence = array();
        
$arrEnd = array();
        foreach(
$delimiters as $key => $value){
            
$position strpos($string$value);
            if(
$position > -1){
                
$arrOccurence[$value] = $position;
            }
        }
        
        if(
count($arrOccurence) > 0){
                
            
asort($arrOccurence);
            
$arrEnd array_values($arrOccurence);
            
array_shift($arrEnd);
    
            
$i 0;
            foreach(
$arrOccurence as $key => $start){
                
$pointer $start+strlen($key);
                if(
$i == count($arrEnd)){
                    
$arrOccurence[$key] = substr($string$pointer);
                } else {
                    
$arrOccurence[$key] = substr($string$pointer$arrEnd[$i]-$pointer);
                } 
                
$i++;
            }
            
        }

         
//next part can be left apart if not necessary. In that case key that don't appear in the inputstringwill not be returned
        
foreach($delimiters as $key => $value){
            if(!isset(
$arrOccurence[$value])){
                
$arrOccurence[$value] = '';
            }
        }

        return 
$arrOccurence;
}
?>

[#9] php at metehanarslan dot com [2013-02-04 22:43:32]

Here is my approach to have exploded output with multiple delimiter. 

<?php

//$delimiters has to be array
//$string has to be array

function multiexplode ($delimiters,$string) {
    
    
$ready str_replace($delimiters$delimiters[0], $string);
    
$launch explode($delimiters[0], $ready);
    return  
$launch;
}

$text "here is a sample: this text, and this will be exploded. this also | this one too :)";
$exploded multiexplode(array(",",".","|",":"),$text);

print_r($exploded);

//And output will be like this:
// Array
// (
//    [0] => here is a sample
//    [1] =>  this text
//    [2] =>  and this will be exploded
//    [3] =>  this also 
//    [4] =>  this one too 
//    [5] => )
// )

?>

[#10] kkobashi at kobashicomputing dot com [2012-07-14 03:36:04]

Explode does not parse a string by delimiters, in the sense that we expect to find tokens between a starting and ending delimiter, but instead splits a string into parts by using a string as the boundary of each part. Once that boundary is discovered the string is split. Whether or not that boundary is proceeded or superseded by any data is irrelevant since the parts are determined at the point a boundary is discovered. 

For example: 

<?php 

var_dump
(explode("/","/")); 

 

?>
 

The reason we have two empty strings here is that a boundary is discovered before any data has been collected from the string. The boundary splits the string into two parts even though those parts are empty. 

One way to avoid getting back empty parts (if you don't care for those empty parts) is to use array_filter on the result. 

<?php 

var_dump
(array_filter(explode("/","/"))); 

 
?>
 

*[This note was edited by googleguy at php dot net for clarity]*

[#11] eye_syah88 at yahoo dot com [2011-05-30 00:32:45]

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 )

[#12] dhz [2010-12-30 09:21:09]

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));
?>

[#13] tiago dot dias at flow-me dot com [2010-09-09 03:40:14]

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
(
)

[#14] Cody G. [2010-08-08 06:41:19]

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.

[#15] m0gr14 at gmail dot com [2010-07-31 07:02:50]

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

?>

[#16] jessebusman at gmail dot com [2010-05-27 12:45:09]

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
}
?>

[#17] locoluis at gmail dot com [2010-04-08 09:02:46]

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.

[#18] gxd305 at gmail dot com [2009-11-16 17:47:31]

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.

[#19] nick dot brown at free dot fr [2009-10-14 15:47:32]

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.

[#20] Jrg Wagner [2009-10-12 14:28:53]

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($resArrarray_pop($resArr) . ($preserve?$enclose:'') . $EncItem.($preserve?$enclose:''));
    }else{
      
$expDelArr explode($delim$EncItem);
      
array_push($resArrarray_pop($resArr) . array_shift($expDelArr));
      
$resArr array_merge($resArr$expDelArr);
    }
  }
  return 
$resArr;
}
?>

[#21] Anonymous [2009-09-28 15:20:42]

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;
    }
?>

[#22] Anonymous [2009-09-02 19:18:59]

<?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($s0$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
)

[#23] Anonymous [2009-08-10 22:55:26]

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";
?>

[#24] SR [2009-04-21 07:50:55]

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.

[#25] Michael [2009-04-19 02:29:23]

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(

   
=> '^255.255.255.255',
   
=> '^255.250',
   
=> '^255.255.250'

  
);

  for (
$i $i sizeof($denied) ; $i++) {

   if (
sizeof(explode($denied[$i], '^' $one '$')) == 2) {
    return 
true;
   }

  }

  return 
false;

 }

 if (
denied($_SERVER['REMOTE_ADDR'])) {
  
header('Location: denied.php');
 }

?>

[#26] pinkgothic at gmail dot com [2007-10-15 02:26:31]

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. :)

[#27] seventoes at gmail dot com [2006-12-09 19:49:00]

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));
?>

[#28] coroa at cosmo-genics dot com [2003-11-16 08:01:29]

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");

上一篇: 下一篇: