codecamp

PHP explode() 函数

PHP explode() 字符串分割为数组函数

PHP String 参考手册 PHP String 参考手册

实例

用自定义分隔符把字符串分割为数组:

<?php
$str = "Hello world w3cschool";
print_r(explode(" ",$str));
?>

运行实例 »

以上输出内容:

Array(
    [0] => Hello
    [1] => world
    [2] => w3cschool
)

定义和用法

explode() 函数把字符串打散为数组。

注释:"separator" 参数不能是一个空字符串。

注释:该函数是二进制安全的。

相关函数implode()用自定义连接符把数组组成字符串


语法

explode(separator,string,limit)

参数 描述
separator 必需。规定在哪里分割字符串。
string 必需。要分割的字符串。
limit 可选。规定所返回的数组元素的数目。

可能的值:

  • 大于 0 - 返回包含最多 limit 个元素的数组
  • 小于 0 - 返回包含除了最后的 -limit 个元素以外的所有元素的数组
  • 0 - 返回包含一个元素的数组

技术细节

返回值: 返回字符串数组。
PHP 版本: 4+
更新日志: 在 PHP 4.0.1 中,新增了 limit 参数。在 PHP 5.1.0 中,新增了对负数 limits 的支持。


更多实例

实例 1

使用 limit 参数来返回一些数组元素:

<?php
$str = 'one,two,three,four';

// zero limit
print_r(explode(',',$str,0));

// positive limit
print_r(explode(',',$str,2));

// negative limit
print_r(explode(',',$str,-1));
?>

运行实例 »

以上输出内容

Array
(
    [0] => one,two,three,four
)

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

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


PHP String 参考手册 PHP String 参考手册
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

PHP 相关教程

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }