0

如何使用 php 拆分字符串并存储到三个不同的数组中?我是php新手,如果可以的话请给我一个详细的答案~

输入将是一个我们不知道它有多长的字符串:

ubuntu1204gui Client myurl/token=something1 windows7 Gateway myurl/token=token=something2 ubuntu1204gui Server myurl/token=token=something3 ...

输出应该是三个数组:

array1[0]= ubuntu1204gui
array1[1]= windows7
array1[2]= ubuntu1204gui
array1[3]= ...
...

array2[0]= Client
array2[1]= Gateway
array2[2]= Server
array2[3]= ...
...

array3[0]=myurl/token=token=something1
array3[1]=myurl/token=token=something2
array3[2]=myurl/token=token=something3
array3[3]=...
...

非常感谢你的帮助!

4

2 回答 2

1
$str = 'ubuntu1204gui Client myurl/token=something1 windows7 Gateway myurl/token=token=something2 ubuntu1204gui Server myurl/token=token=something3';

$arr = [];
foreach(explode(' ', $str) as $key => $value)
{
  $arr[(($key + 1) % 3)][] = $value;
}

var_dump($arr);

Output

array (size=3)
  1 => 
    array (size=3)
      0 => string 'ubuntu1204gui' (length=13)
      1 => string 'windows7' (length=8)
      2 => string 'ubuntu1204gui' (length=13)
  2 => 
    array (size=3)
      0 => string 'Client' (length=6)
      1 => string 'Gateway' (length=7)
      2 => string 'Server' (length=6)
  0 => 
    array (size=3)
      0 => string 'myurl/token=something1' (length=22)
      1 => string 'myurl/token=token=something2' (length=28)
      2 => string 'myurl/token=token=something3' (length=28)
于 2013-09-06T00:31:35.313 回答
0

由于您的字符串有 3 种不同类型的数据,由空格分隔,不幸的是,您需要的不仅仅是一个简单的 explode()。

这是一个片段。

// Declare our string
$string = "ubuntu1204gui Client myurl/token=something1 windows7 Gateway myurl/token=token=something2 ubuntu1204gui Server myurl/token=token=something3";

// First Split the spring up into individual items (using the spaces as delimiter)
// http://php.net/manual/en/function.explode.php
$items = explode(' ',$string);

// setup our target arrays
$array1 = $array2 = $array3 = array();

// Reindex our array to start from 1 (so we can use modulus effectively)
array_unshift($items, "temp");
unset($items[0]);

// Then we loop items & put in right array using the help of our friend modulus!
foreach($items as $key=>$item)
{
  if($key%3==0)
   $array3[] = $item;
  else
  if($key%3==2)
   $array2[] = $item;
  else
   $array1[] = $item;
}

echo'<pre>';
print_r($array1);
print_r($array2);
print_r($array3);

多田!!

Array
(
    [0] => ubuntu1204gui
    [1] => Gateway
    [2] => ubuntu1204gui
)
Array
(
    [0] => Client
    [1] => windows7
    [2] => Server
)
Array
(
    [0] => myurl/token=something1
    [1] => myurl/token=token=something2
    [2] => myurl/token=token=something3
)
于 2013-09-06T01:15:05.397 回答