将文本文件读取为数组

时间:2013-11-21 09:17:52

标签: php arrays

我想将文本文件转换为数组,这是文本文件的样子

code 1 #Updated 12/15/2000
{
Reezena of Confinement
}
code 2 #Added in v2.0
{
Neil
}
code 3 #Added in V1.0
{
Jansen
}
code 4 #Updated 12/15/2000
{
Gellos
}

完成后它应该是什么样的

array(
'1' => "Reezena of Confinement",
'2' => "Neil",
'3' => "Jansen",
'4' => "Gellos",
)

我试过这个:

preg_match_all('/{(.*?)}/s', $html, $matches);

//HTML array in $matches[1]
echo "<pre>";
print_r($matches[1]);
echo "</pre>";

然而它错过了“代码XXX” 不知怎的,我需要抓住它

事先提前

3 个答案:

答案 0 :(得分:0)

利用PHP上的file()

<?php
$arr=file('new.txt'); //Save all the content what you pasted in a file named new.txt
for($i=2;$i<count($arr);$i=$i+4)
{
    echo $arr[$i];
    echo "<br>";
}

<强>输出:

Reezena of Confinement 
Neil 
Jansen 
Gellos

答案 1 :(得分:0)

试试这个:

    $str = file_get_contents ( 't.txt' );

    preg_match_all ( '@code\s+(\d+)[^{]*{([^}]+)}@', $str, $matches );

    $result = array ();

    foreach ( $matches [1] as $k => $id )
    {
        $result [$id] = trim ( $matches [2] [$k] );
    }

    var_dump ( $result );

答案 2 :(得分:0)

我的解决方案没有任何preg类功能;

$txt = "code 1 #Updated 12/15/2000
{
Reezena of Confinement
}
code 2 #Added in v2.0
{
Neil
}
code 3 #Added in V1.0
{
Jansen
}
code 4 #Updated 12/15/2000
{
Gellos
}";


$lines = explode("\n", $txt);

$array = array();
$key = NULL;

foreach($lines as $line) {
    if(trim($line) === '{' || trim($line) === '}') {
        continue;
    }
    if(substr($line, 0, 4) == 'code') {
        $exploded = explode(' ', $line);
        $key = $exploded[1];
        continue;
    }
    if(isset($key)) {
        $array[$key] = $line;
        $key = NULL;
    }
}
echo "<pre>";
print_r($array);
echo "</pre>";

结果;

Array
(
    [1] => Reezena of Confinement
    [2] => Neil
    [3] => Jansen
    [4] => Gellos
)