我有一个字符串,它使用空格作为分隔符分解为数组。例如,是否有可能将前4个单词分解为数组,将其余单词分解为ONE数组元素?
截至目前,代码就像这样
$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
[7] => be
[8] => split
[9] => into
[10] => elements
)
我需要的是数组看起来像这样
Array
(
[0] => This
[1] => is
[2] => a
[3] => string
[4] => that
[5] => needs
[6] => to be split into elements
)
这样的事情可能吗?
答案 0 :(得分:4)
在此处使用limit
参数。
来自 explode()
文档:
如果设置了limit并且为正数,则返回的数组将包含最多限制元素,最后一个元素包含其余字符串。
代码:
$string = 'This is a string that needs to be split into elements';
$splitarray = explode(' ',$string, 7);
print_r($splitarray);
输出:
Array
(
[0] => This
[1] => is
[2] => a
[3] => string
[4] => that
[5] => needs
[6] => to be split into elements
)