你如何在PHP中的数组中添加一行

时间:2013-06-11 21:08:01

标签: php

我在php中有如下所示的$行

33 0 0 51037280 396822 15 16 0 0 0 0 20907 143197 57377 27 12 51 10 7.33 45.8 17:07:31

我尝试创建和数组,并将每个按空格分隔的值放到这个数组中,如下所示:

$parts=explode(" ", $line)

应该有20个索引,这个$ line上有21个coluns。但是当我这样做时:

   $size=sizeof($parts)

echo $ size返回58,这怎么可能。有没有更好的方法将$ line中的项插入到数组中?看起来值之间存在不规则的空格量。当我这样做时:

的print_r($份)

我得到以下内容:

[0] => [1] => 33 [2] => [3] => [4] => 0 [5] => [6] => [7] => 0 [8] => [9] => [10] => 51037280 [11] => [12] => [13] => [14] => [15] => 396822 [16] => [17] => [18] => [19] => 15 [20] => [21] => [22] => [23] => 16 [24] => [25] => [26] => [27] => [28] => 0 [29] => [30] => [31] => [32] => [33] => 0 [34] => [35] => [36] => [37] => [38] => 0 [39] => [40] => [41] => [42] => [43] => [44] => 0 [45] => 20907 [46] => 143197 [47] => 57377 [48] => 27 [49] => 12 [50] => 51 [51] => 10 [52] => [53] => 7.33 [54] => [55] => 45.8 [56] => 17:07:31 )

如何忽略值之间的空格数并将每个值存储为php中的数组值?

3 个答案:

答案 0 :(得分:1)

确保元素之间只有一个空格,字符串的开头或结尾没有空格,然后拆分字符串:

 $line = trim($line);
 $line = preg_replace('/\s\s+/', ' ', $line);
 $parts=explode(" ", $line)

答案 1 :(得分:0)

可能会出现多个空格。

尝试

 $parts = preg_split('/\s+/', $line);

答案 2 :(得分:0)

您可以稍后过滤掉空字符串,但更容易做到这一点:

preg_split('/ +/',$string,-1, PREG_SPLIT_NO_EMPTY);