所以我有这些文本文件,其中包含一些细节,我希望PHP能够单独提取和分发每个数据。
文本文件的示例数据:
Plugin Name: Sample Framework
Description: This is a sample framework
Author: User Friendly
我想要的是从特定标签中获取每个数据,例如,如果我想获得"插件名称",那么预期结果将是:
Sample Framework
如果我想获得描述:
This is a sample framework
但我不知道该怎么做。 preg_replace或preg_match可能会有效,但是如果有关于文本文件的隆隆声数据,我认为这不会有效,但我愿意接受任何答案。
我还有这个现有的功能来确定我想要显示的细节类型。
见下面的例子:
<?php
function getDetails($var){
if($var=='pname'){
//get the plugin name
}
} ?>
我认为有很多平台可以做到,但我无法弄明白。
答案 0 :(得分:3)
这应该适合你:
只需将您的文件读入包含file()
的数组,然后将第一行作为键提取,将另一行作为数据提取,然后您可以array_combine()
一起提取。
<?php
$lines = file("test.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$lines = array_map(function($v){
return explode(":", $v);
}, $lines);
$data = array_combine(array_map("array_shift", $lines), array_map("array_pop", $lines));
print_r($data);
?>
输出:
Array
(
[Plugin Name] => Sample Framework
[Description] => This is a sample framework
[Author] => User Friendly
)