使用PHP的explode()函数将字符串拆分为数组

explode()函数可以将字符串拆分为数组。将字符串拆分为数组时,将根据分隔符对字符串进行拆分。

explode()函数可以正确处理字符串中的空字节。

基本语法

explode(separator,string,limit)

separator指定用于分隔字符串的分隔符。指定分隔符,但不能指定“空”分隔符。如果指定,将出现以下错误:Warning: explode(): Empty delimiter。

string 指定要拆分的字符串。

limit 指定要返回的数组元素的数量。可能的值有“大于0(返回最大限制元素的数组)”、“小于0(删除数组的最后N个元素并返回数组的其余部分)”、“0(返回的数组有一个元素,即返回整个字符串)”。

使用PHP的explode()函数将字符串拆分为数组  第1张

explode()函数

现在,让我们使用 PHP 的 explode() 函数来写几个实例。

1.指定“空”分隔符的错误写法

$str = "香蕉,橘子,苹果,葡萄,水蜜桃";
print_r(explode("",$str));

执行结果

Warning: explode(): Empty delimiter in D:\ciyawang\test.php on line 8

使用PHP的explode()函数将字符串拆分为数组  第2张

2.explode()函数正确写法

$str = "香蕉,橘子,苹果,葡萄,水蜜桃";
print_r(explode(",",$str));

执行结果

Array ( [0] => 香蕉 [1] => 橘子 [2] => 苹果 [3] => 葡萄 [4] => 水蜜桃 )

使用PHP的explode()函数将字符串拆分为数组  第3张

使用limit参数指定数组中的元素数

接下来,使用limit参数来指定数组中元素的数量。

1.返回包含一个元素的数组

$str = "香蕉,橘子,苹果,葡萄,水蜜桃";
print_r(explode(',',$str,0));

执行结果

Array ( [0] => 香蕉,橘子,苹果,葡萄,水蜜桃 )

使用PHP的explode()函数将字符串拆分为数组  第4张

2.数组元素为 2

$str = "香蕉,橘子,苹果,葡萄,水蜜桃";
print_r(explode(",",$str,2));

执行结果

Array ( [0] => 香蕉 [1] => 橘子,苹果,葡萄,水蜜桃 )

使用PHP的explode()函数将字符串拆分为数组  第5张

3.删除最后一个数组元素

$str = "香蕉,橘子,苹果,葡萄,水蜜桃";
print_r(explode(",",$str,-1));

执行结果

Array ( [0] => 香蕉 [1] => 橘子 [2] => 苹果 [3] => 葡萄 )

使用PHP的explode()函数将字符串拆分为数组  第6张

使用explode()函数的limit参数,str变量内的字符串在这里被替换,可以看到被分割成了指定数量的元素。

本文来源:词雅网

本文地址:https://www.ciyawang.com/php-explode-array.html

本文使用「 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 」许可协议授权,转载或使用请署名并注明出处。

相关推荐