PHP使用爆炸

时间:2012-08-12 13:54:26

标签: php arrays split explode

我试图爆炸并将结果分成两个不同的数组

One One_x
Two Two_xx
Three Three_xxx
Four Four_xxxx

我首先要爆炸断裂线(\ n)..
然后爆炸空间以在阵列中提出所有一,二,三,四 AND One_x,Two_xx,Three_xxx,Four_xxxx 在不同的阵列中

我试图爆炸断裂线

$ex = explode("\n", $numbers);

然后

foreach($ex as $number){
  $ex = explode(" ", $number);
}

但对我来说似乎有点混乱,

如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

$array1 = array();
$array2 = array();
foreach($ex as $number){
  $tmp = explode(" ", $number);
  $array1[] = $tmp[0];
  $array2[] = $tmp[1];
}

我认为最简单的方式

编辑:关心你在循环中设置$ex ...不是一个好主意。使用另一个var

答案 1 :(得分:1)

而不是runnig一次或两次爆炸,正则表达式可以立即拆分输入,并在其上断言结构:

 preg_match_all('/
         ^         # line start
         (\w+)     # One, Two, ...
         \s+       # spaces
         (\w+)     # Four_xxxxx
         $         # line end
      /smix',
      $input,
      $array
 );
 print_r($array);

会给你:

[0] => Array
    (
        [0] => One One_x
        [1] => Two Two_xx
        [2] => Three Three_xxx
        [3] => Four Four_xxxx
    )

[1] => Array
    (
        [0] => One
        [1] => Two
        [2] => Three
        [3] => Four
    )

[2] => Array
    (
        [0] => One_x
        [1] => Two_xx
        [2] => Three_xxx
        [3] => Four_xxxx
    )

还可以使用PREG_SET_ORDER甚至提取尾随的_xxxx(?)数字。