首页 > 解决方案 > 当文件的部分被换行符分割时,如何将 file_get_contents 的输出转换为数组?

问题描述

我有一个始终采用这种格式的file_get_contents的更改日志:

*** Product Name Changelog ***

2020-12-25 - version 1.0.2
* Some text
* Some text
* Some text
* Some text
* Some text

2020-12-20 - version 1.0.1
* Some text
* Some text
* Some text
* Some text
* Some text

2020-12-15 - version 1.0.0
* Some text
* Some text
* Some text
* Some text
* Some text

我想把它变成这样的数组:

array(
    '1.0.2' => array(
        'date' => '2020-12-25',
        'entry' => '[the bullet html]'
    ),
    '1.0.1' => array(
        'date' => '2020-12-20',
        'entry' => '[the bullet html]'
    ),
    '1.0.0' => array(
        'date' => '2020-12-15',
        'entry' => '[the bullet html]'
    )
)

我已经尝试过了,但只是真正找到了一种使用以下方法提取最新版本的方法:

<?php function getVersion($str) {
    preg_match("/(?:version)\s*((?:[0-9]+\.?)+)/i", $str, $matches);
    return $matches[1];
}

echo 'latest version is: ' . getVersion($changelog); // gets latest version ?>

我正在尝试做的事情可能吗?我怀疑我需要通过每个版本之间的空白行以某种方式将其拆分,然后从这些部分进一步增加数据?

标签: phparraysfile-get-contents

解决方案


有关解释,请参阅代码中的注释。

$input = '*** Product Name Changelog ***

2020-12-25 - version 1.0.2
* Some text
* Some text
* Some text
* Some text
* Some text

2020-12-20 - version 1.0.1
* Some text
* Some text
* Some text
* Some text
* Some text

2020-12-15 - version 1.0.0
* Some text
* Some text
* Some text
* Some text
* Some text';

$lines = preg_split('/\R/',$input);  //lines -> array
$lines = array_slice($lines,2);  //remove title

$result = [];
$arr = [];
foreach($lines as $line){
  if( preg_match('/^(\d{4}-\d\d-\d\d)[\- ]+version ([\d.]+)/',$line,$match)){
    //date + version
    if(!empty($arr)) $result[] = $arr;
    $arr = [
      'date' => $match[1],
      'version' => $match[2],
      'entry' => ''
     ]; 
  }
  else {
    // some text
    $arr['entry'] .= $line.'<br>';
  }
}

//save last
if(!empty($arr)) $result[] = $arr;

//sort latest version
usort($result, function($a,$b){
  return version_compare($b['version'], $a['version']);
});

$latestVersion = $result[0];
var_dump($latestVersion);

输出:

array(3) { ["date"]=> string(10) "2020-12-25" ["version"]=> string(5) "1.0.2" ["entry"]=> string(79) "* Some text
* Some text
* Some text
* Some text
* Some text

" }

推荐阅读