(PHP 4, PHP 5)
explode — 使用一个字符串分割另一个字符串
$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
参数之前才行。
Note:
参数
limit
是在 PHP 4.0.1 中加入的。
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 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: 此函数可安全用于二进制对象。
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.
Returns an array of strings
created by splitting the string
parameter on
boundaries formed by the delimiter
.
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, otherwise an array containing
string
will be returned.
版本 | 说明 |
---|---|
5.1.0 |
Support for negative limit s was added
|
4.0.1 |
The limit parameter was added
|
Example #3 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 #4 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));
?>
以上例程会输出:
Array ( [0] => one [1] => two|three|four ) Array ( [0] => one [1] => two [2] => three )
Note: 此函数可安全用于二进制对象。