文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>explode

explode

时间:2007-12-14  来源:061107


explode
(PHP 4, PHP 5)
explode — 使用一个字符串分割另一个字符串
说明array explode ( string $separator, string $string [, int $limit] )
此函数返回由字符串组成的数组,每个元素都是 string 的一个子串,它们被字符串 separator 作为边界点分割出来。如果设置了 limit 参数,则返回的数组包含最多 limit 个元素,而最后那个元素将包含 string 的剩余部分。
如果 separator 为空字符串(""),explode() 将返回 FALSE。如果 separator 所包含的值在 string 中找不到,那么 explode() 将返回包含 string 单个元素的数组。
如果 limit 参数是负数,则返回除了最后的 -limit 个元素外的所有元素。此特性是 PHP 5.1.0 中新增的。
由于历史原因,虽然
implode()
可以接收两种参数顺序,但是 explode() 不行。你必须保证 separator 参数在 string 参数之前才行。
注意: 参数 limit 是在 PHP 4.0.1 中加入的。
例 2221. explode() 例子
// 示例 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; // *
?>
例 2222. limit 参数例子
= '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
)
   
注意: 本函数可安全用于二进制对象。
参见
preg_split()

spliti()

split()

strtok()

implode()

fprintf" src="http://www.phpq.net/images/caret-r.gif" width=11>



echo

User Contributed Notes explode
pinkgothic at gmail dot com
15-Oct-2007 05: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. :)
mraheel83 at gmail dot com
24-Sep-2007 04:45

= "SELECT * FROM `orders_status` Where status = 'enabled'";  
                                            $result = mysql_query($query);  
                                            $counter = 0;
                                            $orderStatusRecords = explode(",",$_REQUEST['orderStatus']);
                                            
                                            while($row = mysql_fetch_array($result)) {
                                            echo $orderStatusRecords[$counter];
                                        ?>
                                            ['id']?>" if($row['id'] == $orderStatusRecords[$counter]) {?> checked="checked" } ?> /> ['title']?>  
                                        ++;
                                        } ?>
You can checked selected checkbox by using above explode + while loop combination
thomas at tgohome dot com
26-Jul-2007 05: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:
= "";
$numbers = explode(",", $string); // Array with one element, "".
$string = "1,2,3";
$numbers = explode(",", $string); // Array with three elements
?>
tajhlande at gmail dot com
20-Jun-2007 08: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.
// 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;
}
?>
IanB
25-May-2007 10: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
tobylewis at logogriph dot com
25-May-2007 05: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.
xangelusx at hotmail dot com
17-May-2007 11:45

@ JJ Rock, jason dot minett:
Here's an easy way around that:
= '^one^two^three^';
//Use trim() to remove extra delimiters
$arr = explode ('^', trim($str, '^'));
?>
JJ Rock
27-Apr-2007 07: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:
= "^one^two^three";
$arr = explode ("^", $str);
?>
results in an empty value in $arr[0].
user at nospam dot com
27-Apr-2007 05:08

// 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
?>
Q1712 at online dot ms
23-Apr-2007 09: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.
Q1712 at online dot ms
22-Apr-2007 11: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.
( explode( "|", "one|two|three|four", 0) );
print_r( explode( "|", "one|two|three|four", 1) );
?>
both print:
Array
(
    [0] => one|two|tree|four
)
( explode( "|", "one|two|three|four", -4) );
print_r( explode( "|", "one|two|three|four", -5) );
?>
both print:
Array
(
)
jason dot minett at custoREMOVEmscripts dot co dot uk
02-Mar-2007 12: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):
= "aaa^elephant^chocolate^albatross^";
$arr = explode ("^", $str);
echo ("Array length: ".count($arr));
?>
---------------------------------
Array length: 5
Nicoxinchao
28-Feb-2007 03:59

insensitive case explode function:
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;   
    }
?>
orlandu96 at gmail dot com
17-Dec-2006 01:28

A 'between' function that we've all been waiting for. I am not savvy with regex so I resorted to explode();
function between($beg, $end, $str) {
$a = explode($beg, $str, 2);
$b = explode($end, $a[1]);
return $beg . $b[0] . $end;
}
echo between('', '', 'fsdfsdfsdfsdfsdsdfsdfsdf')
//fsdfsd
?>
seventoes at gmail dot com
10-Dec-2006 11:49

Note that explode, split, and functions like it, can accept more than a single character for the delimiter.
= "Something--next--something else--next--one more";
print_r(explode('--next--',$string));
?>
Elad Elrom
21-Oct-2006 02: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,"
");
function LimitText($Text,$Min,$Max,$MinAddChar) {
    if (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;
}
webmaster at saund-web dot com
14-Mar-2006 02: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 $pound . $pence\n";
djogo_curl at yahoo
01-Dec-2004 08: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.
ian at illumen dot co dot uk
24-Aug-2004 04:30

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.
= '';
$foo = explode( ":", $str );
print_r( $foo );
$foo = split( ":", $str );
print_r( $foo );
$foo = preg_split( "/:/", $str );
print_r( $foo );
?>
In all three cases prints
Array
(
� � [0] =>
)
This of course means that you must explicitly check to see if the value of the first element is blank, or must check to see if the string being split is blank.
coroa at cosmo-genics dot com
17-Nov-2003 12: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");

相关阅读 更多 +
排行榜 更多 +
翌日波奇狗的历险记手机版下载

翌日波奇狗的历险记手机版下载

休闲益智 下载
怪兽远征安卓版下载

怪兽远征安卓版下载

角色扮演 下载
谷歌卫星地图免费版下载

谷歌卫星地图免费版下载

生活实用 下载