我想将文件读入数组并将文件中的某些内容用作数组键。
示例
myfile.txt
[SPLIT]
#START:KEY1
this is the content
#END:KEY1
[SPLIT]
#START:KEY2
this is the next content
#END:KEY2
...
我从文件中加载内容
$File = file_get_contents(myfile.txt);
我在制造商[SPLIT]上分割了内容并创建了一个数组
$file_array = explode('[SPLIT]',$File);
foreach($file_array as $element)
{
//search for '#START:' get the part after that till lineend, use this as ($key) a key for a new array
....
$new[$key]=$element;
}
所以,我的问题是,有没有一种更简单或更快速的方法,可以根据看起来像的文件内容创建数组?
$myarray[KEY1]=this is the content
$myarray[KEY2]=this is the next content
答案 0 :(得分:3)
您是否尝试过使用常规表达式?
$content = file_get_contents('file_name.txt');
preg_match_all('/\[SPLIT\]\n#START:(.*?)\n(.*?)#END/s', $content, $rows);
$data = [];
foreach ($rows[1] as $i => $key) {
$data[$key] = trim($rows[2][$i]);
}
答案 1 :(得分:0)
这将基于新行拆分:
$File = file('tmp/myfile.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);