开发者

help with looping in php

I have a need of scraping information from text files that comes in format like so: I know how to get the delimiter from between the quotes. using that delimiter i have to go through each se开发者_JAVA技巧ction, and set the name in one variable and information between delimiter in another variable. Need to continue doing until it reaches end of file.

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

--@--

End of file

i appreciate all the help i get. Thanks!


If I've understood what you're trying to do, this should do what you need.

<?
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.
}

Simpler methods are possible using file_get_contents but depending on how large your file is that may not be possible since you would have to load the whole file into memory.


considering your text file content is in $string and delimiter is $delim, a preg_match_all and a array_combine will help you with this

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

it should return somthing like this:

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
)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜