2013-08-07 13 views
0

我有一个字符串,它使用空格作为分隔符分解到一个数组中。例如,是否有可能将前4个单词分解为数组,其余单元分解为1个数组元素?PHP将字符串的第一部分分解为数组元素,将第二部分分解为一个元素

为现在的代码是这样的

$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 

    ) 

是什么这可能吗?

+2

阅读手册,['爆炸()'](http://php.net/manual/en/function.explode .php)有第三个选项:'数组explode(字符串$ delimiter,字符串$ string [,** int $ limit **])':) – HamZa

+0

当然是极限!谢谢:) –

回答

3

在此处使用limit参数。

explode()文档:

如果限制设置和肯定的,则返回的数组将一个最大限制元件的包含与包含字符串的其余部分的最后一个元素。

代码:

$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 
) 
+0

是的。不能相信我忽略了那么简单的事情。 –

+0

@RonaldFernandes:如果这回答了您的问题,您可以将其标记为*接受*。干杯:) –

相关问题