php - 当文件的部分被换行符分割时,如何将 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 ?>
我正在尝试做的事情可能吗?我怀疑我需要通过每个版本之间的空白行以某种方式将其拆分,然后从这些部分进一步增加数据?
解决方案
有关解释,请参阅代码中的注释。
$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
" }
推荐阅读
- powershell - 基于变量的投射
- c# - UWP MediaCapture 初始化失败
- ssh - 如何在不使用临时外部 IP 的情况下使用 Pycharm 与 GCP VM 进行 SSH?
- key - ETCD 键名 - 支持哪些字符?
- flutter - 在 StreamBuilder 上将小部件居中
- javascript - JavaScript:三个下拉菜单,一个 onchange()。一个下拉列表更改,更改另一个下拉列表
- javascript - 如何从 Typescript 中响应的特定属性分配表数据源?
- java - 弹性搜索多重匹配得到错误的结果
- bash - 想要从容器注册表中过滤 gcp docker 镜像摘要
- python - 在 PySpark 日期列中获取每年的最新日期