1

我有一个字符串,它使用空格作为分隔符分解成一个数组。例如,是否可以将前 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

    )

这样的事情可能吗?

4

1 回答 1

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
)
于 2013-08-07T08:33:47.580 回答