从数组中拆分字符串行

时间:2014-09-17 14:41:50

标签: php arrays

我有以下带字符串行的数组:

array(12) {
  [0]=>
  string(27) "Kungsvägen 118 A 1969-06-17"
  [1]=>
  string(24) "Skolgatan 1 B 1969-06-17"
  [2]=>
  string(24) "Skolgatan 1 B 1980-05-22"
  [3]=>
  string(22) "Myntvägen 8 1980-05-22"
  [4]=>
  string(24) "Skolgatan 1 B 1993-05-09"
  [5]=>
  string(24) "Skolgatan 1 B 1989-06-28"
  [6]=>
  string(24) "Skolgatan 1 B 1991-03-17"
  [7]=>
  string(24) "Skolgatan 1 B 1989-10-30"
  [8]=>
  string(33) "Gasslanda VÄSTERGÅRD 2 1980-10-30"
  [9]=>
  string(24) "Skolgatan 1 B 1980-10-30"
  [10]=>
  string(24) "Skolgatan 1 B 1990-05-01"
  [11]=>
  string(21) "Ågatan 6 A 1990-05-01"
}

该字符串包含地址和出生日期。我想分开/分开这两个。我怎么能用PHP做到这一点?

2 个答案:

答案 0 :(得分:0)

这可能有助于你

$ar = array(
  0=>"Kungsvägen 118 A 1969-06-17",
  1=>"Skolgatan 1 B 1969-06-17",
  2=>"Skolgatan 1 B 1980-05-22",
  3=>"Myntvägen 8 1980-05-22",
  4=>"Skolgatan 1 B 1993-05-09",
  5=>"Skolgatan 1 B 1989-06-28",
  6=>"Skolgatan 1 B 1991-03-17",
  7=>"Skolgatan 1 B 1989-10-30",
  8=>"Gasslanda VÄSTERGÅRD 2 1980-10-30",
  9=>"Skolgatan 1 B 1980-10-30",
  10=>"Skolgatan 1 B 1990-05-01",
  11=>"Ågatan 6 A 1990-05-01"
);

foreach ($ar as $key => $value) {
    $arr[$key]['address'] = substr($value, 1,-10);
    $arr[$key]['dob'] = substr($value, -10);
}
print_r($arr);

<强>输出

Array
(
    [0] => Array
        (
            [address] => ungsvägen 118 A 
            [dob] => 1969-06-17
        )

    [1] => Array
        (
            [address] => kolgatan 1 B 
            [dob] => 1969-06-17
        )

    [2] => Array
        (
            [address] => kolgatan 1 B 
            [dob] => 1980-05-22
        )

    [3] => Array
        (
            [address] => yntvägen 8 
            [dob] => 1980-05-22
        )

    [4] => Array
        (
            [address] => kolgatan 1 B 
            [dob] => 1993-05-09
        )

    [5] => Array
        (
            [address] => kolgatan 1 B 
            [dob] => 1989-06-28
        )

    [6] => Array
        (
            [address] => kolgatan 1 B 
            [dob] => 1991-03-17
        )
  ..... upto last element

答案 1 :(得分:0)

首先通过将日期作为分隔符来获取地址,然后获取日期。

$final = array();
foreach($inputarr as $value) {
  $address = preg_split('/(\d{4}-\d{2}-\d{2})/', $value);
  preg_match('/(\d{4}-\d{2}-\d{2})/', $value, $date);
  array_push($final, array($address[0], $date[0])); 
}

var_dump($final);