使用PHP拆分字符串

时间:2013-09-06 00:20:24

标签: php

如何使用php拆分字符串并存储到三个不同的数组? 我对php很新,所以如果可以,请给我一个详细的答案〜

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

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

和out put应该是三个数组:

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]=...
...

非常感谢你的帮助!

2 个答案:

答案 0 :(得分: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);

输出

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)

答案 1 :(得分:0)

由于你的字符串有三种不同类型的数据用空格分隔,所以不幸的是你需要的不仅仅是一个简单的爆炸()。

这是一个片段。

// 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
)