将字符串分成关联数组

时间:2016-08-06 15:00:06

标签: php arrays split associative-array preg-split

我有一个字符串:

$string = 'A0695/16 NOTAMN Q) EHAA/QARLT/I /NBO/E /000/999/5155N00430E073 A) EHAA B) 1605260001 C) 1608260900 EST E) REF AIP NETHERLANDS ENR 3.2 UT601 ADD TO ROUTE REMARKS: NOT AVBL FOR TRAFFIC DEP/ARR ETNG, EDDK AND ETNN DURING THE OPENING OF EHEH 0600-2300 (0500-2200). THESE FLIGHTS WILL HAVE TO REROUTE.';

我想将此字符串拆分为关联数组。

$result['Q)'] = 'EHAA/QARLT/I /NBO/E /000/999/5155N00430E073';
$result['A)'] = 'EHAA';
$result['B)'] = '1605260001';
$result['C)'] = '1608260900 EST';

我设法将它变成了一个数组:

$result = preg_split("/.\)/", $string);

它给了我一个数组,但我需要键是'a)', 'b)'等。

任何人都可以帮我吗?

3 个答案:

答案 0 :(得分:2)

使用expected expression in the list of expressions and this error expexted ',' separator 函数的解决方案具有特定的正则表达式模式(名为子掩码)和preg_match_all函数(以获取相应的键/值对):

array_combine

输出:

$string = 'A0695/16 NOTAMN Q) EHAA/QARLT/I /NBO/E /000/999/5155N00430E073 A) EHAA B) 1605260001 C) 1608260900 EST E) REF AIP NETHERLANDS ENR 3.2 UT601 ADD TO ROUTE REMARKS: NOT AVBL FOR TRAFFIC DEP/ARR ETNG, EDDK AND ETNN DURING THE OPENING OF EHEH 0600-2300 (0500-2200). THESE FLIGHTS WILL HAVE TO REROUTE.';

preg_match_all("/(?<k>[A-Z]\)) (?<v>.+?)(?= [A-Z]\)|$)/", $string, $matches);

// 'k'/'v' are key/value
$result = array_combine($matches['k'], $matches['v']);

print_r($result);

答案 1 :(得分:1)

愚蠢格式的另一个愚蠢的解决方案,因为为什么不。

  $string = 'A0695/16 NOTAMN Q) EHAA/QARLT/I /NBO/E /000/999/5155N00430E073 A) EHAA B) 1605260001 C) 1608260900 EST E) REF AIP NETHERLANDS ENR 3.2 UT601 ADD TO ROUTE REMARKS: NOT AVBL FOR TRAFFIC DEP/ARR ETNG, EDDK AND ETNN DURING THE OPENING OF EHEH 0600-2300 (0500-2200). THESE FLIGHTS WILL HAVE TO REROUTE.';

  $foo = preg_split('/([A-Z]\)) /', $string, 0, PREG_SPLIT_DELIM_CAPTURE);
  $ret = [];
  foreach (range(1, count($foo) - 1, 2) as $i)
  {
    $ret[$foo[$i]] = $foo[$i + 1];
  }
  print_r($ret);

打印:

Array (
    [Q)] => EHAA/QARLT/I /NBO/E /000/999/5155N00430E073 
    [A)] => EHAA 
    [B)] => 1605260001 
    [C)] => 1608260900 EST 
    [E)] => REF AIP NETHERLANDS ENR 3.2 UT601 ADD TO ROUTE REMARKS: NOT AVBL FOR TRAFFIC DEP/ARR ETNG, EDDK AND ETNN DURING THE OPENING OF EHEH 0600-2300 (0500-2200). THESE FLIGHTS WILL HAVE TO REROUTE. )

答案 2 :(得分:0)

比有效率更有幻想,但它确实起到了作用:

$p = preg_split('~(?<!\S)([A-Z]\))\s+~', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
$result = [];
if (count($p) > 1) {
    unset($p[0]);
    while($p) { 
        $result[array_shift($p)] = array_shift($p);
    }
}

print_r($result);