PHP将字符串的第一部分分解为数组元素,将第二部分分解为一个元素
我有一个字符串,它被分解成一个数组,使用空格作为分隔符。例如,是否可以将前4个字分解为数组,将其余的字分解为一个数组元素 到目前为止,代码是这样的PHP将字符串的第一部分分解为数组元素,将第二部分分解为一个元素,php,Php,我有一个字符串,它被分解成一个数组,使用空格作为分隔符。例如,是否可以将前4个字分解为数组,将其余的字分解为一个数组元素 到目前为止,代码是这样的 $string = 'This is a string that needs to be split into elements'; $splitarray = explode(' ',$string); Array ( [0] => This [1] => is [2] =>
$string = 'This is a string that needs to be split into elements';
$splitarray = explode(' ',$string);
Array
(
[0] => This
[1] => is
[2] => a
[3] => string
[4] => that
[5] => needs
[6] => to be split into elements
)
这给出了一个数组
Array
(
[0] => This
[1] => is
[2] => a
[3] => string
[4] => that
[5] => needs
[6] => to
[7] => be
[8] => split
[9] => into
[10] => elements
)
我需要的是让数组看起来像这样
$string = 'This is a string that needs to be split into elements';
$splitarray = explode(' ',$string);
Array
(
[0] => This
[1] => is
[2] => a
[3] => string
[4] => that
[5] => needs
[6] => to be split into elements
)
这样做可能吗?在此处使用
limit
参数
从文档:
如果limit设置为正,则返回的数组将包含最多个limit元素,最后一个元素包含字符串的其余部分
代码:
输出:
Array
(
[0] => This
[1] => is
[2] => a
[3] => string
[4] => that
[5] => needs
[6] => to be split into elements
)
在此处使用
limit
参数
从文档:
如果limit设置为正,则返回的数组将包含最多个limit元素,最后一个元素包含字符串的其余部分
代码:
输出:
Array
(
[0] => This
[1] => is
[2] => a
[3] => string
[4] => that
[5] => needs
[6] => to be split into elements
)
阅读手册,有第三个选项:
数组分解(string$delimiter,string$string[,**int$limit**])
:)当然是限制!谢谢:)阅读手册,有第三个选项:数组分解(string$delimiter,string$string[,**int$limit**])
:)当然是限制!谢谢:)是的。真不敢相信我忽略了这么简单的事情。真不敢相信我忽略了这么简单的事情。