explode(separator, string, limit)
explode() 函数把字符串打散为数组。
注释:”separator” 参数不能是空字符串。
注释:该函数是二进制安全的。
| 参数 | 描述 |
|---|---|
| separator | 必需。规定在哪里分割字符串。 |
| string | 必需。要分割的字符串。 |
| limit | 可选。规定所返回的数组元素的数目。 |
limit可能的值:
大于 0 – 返回包含最多 limit 个元素的数组
小于 0 – 返回包含除了最后的-limit个元素以外的所有元素的数组
0 – 返回包含一个元素的数组
$str = "Hello world. I love Shanghai!";
$result=explode(".",$str);
dump($result);
# 运行结果
array(2) {
[0] => string(11) "Hello world"
[1] => string(17) " I love Shanghai!"
}
strtok(string, split)
按单词分割字符串:
在下面的实例中,请注意,我们仅在第一次调用 strtok() 函数时使用了 string 参数。在首次调用后,该函数仅需要 split 参数,这是因为它清楚自己在当前字符串中所在的位置。如需分割一个新的字符串,请再次调用带 string 参数的 strtok():
$string = "Hello world. Beautiful day today.";
$token = strtok($string, " ");
while ($token != false) {
echo "$token<br>";
$token = strtok(" ");
}
# 运行结果
Hello
world.
Beautiful
day
today.
str_split(string, length)
str_split() 函数把字符串分割到数组中。
返回值:
如果 length 小于 1,则 str_split() 函数将返回 FALSE。
如果 length 大于字符串的长度,则整个字符串将作为数组的唯一元素返回。
$string = "Hello world. Beautiful day today.";
$result=str_split($string,5);
dump($result);
# 运行结果:
array(7) {
[0] => string(5) "Hello"
[1] => string(5) " worl"
[2] => string(5) "d. Be"
[3] => string(5) "autif"
[4] => string(5) "ul da"
[5] => string(5) "y tod"
[6] => string(3) "ay."
}