帮助在PHP中循环

时间:2011-06-27 14:20:58

标签: php parsing loops

我需要从文本文件中抓取信息,格式如下: 我知道如何从引号之间获取分隔符。使用该分隔符我必须遍历每个部分,并在一个变量中设置名称,在另一个变量中设置分隔符之间的信息。需要继续执行,直到它到达文件末尾。

test.txt
-------------------------
delimiter: "--@--"

--@-- 

name:"section1"

This is section 1 with some information

--@--

name:"section2"

This is section 2 with some information

--@--

name:"section3"

this is section 3 with some information

--@--

文件结束

我感谢所有帮助。谢谢!

2 个答案:

答案 0 :(得分:1)

如果我明白你要做什么,这应该做你需要的。

<?
define(DELIMITER, '--@--');
$fh = fopen('test.txt');
$sections = array();
while ($line = fgets($fh)) {
    if ($line == DELIMITER)
        continue;
    $matches = array();
    if (preg_match('/name:"(.*)"/i', $line, $matches)) {
        $cursect = $matches[1];
        continue;
    }
    $sections[$cursect] .= $line;
}
fclose($fh);

foreach($sections as $name => $content) {
    // Do processing here.
}

使用file_get_contents可以实现更简单的方法,但取决于文件的大小,这可能是不可能的,因为您必须将整个文件加载到内存中。

答案 1 :(得分:0)

考虑到你的文本文件内容在$ string中,分隔符是$ delim,preg_match_all和array_combine将帮助你解决这个问题

$delim = preg_quote($delim,'/');
preg_match_all('/(?<='.$delim.')\s*name:"([^"]+)"\s*(.*?)\s*(?='.$delim.')/',$string,$m);
$items = array_combine($m[1],$m[2]);

它应该返回这样的东西:

Array
(
    [section1] => This is section 1 with some information
    [section2] => This is section 2 with some information
    [section3] => this is section 3 with some information
)
相关问题