0

我必须为具有如下结构的 txt 文件编写解析器:

exampleOfSomething: 95428, anotherExample: 129, youNeedThis: 491,\n

另一个例子:30219,exampleOfSomething:4998,youNeedThis:492,

但是有一个主要问题 - 就像在示例中一样 - 文件并不总是以一个顺序出现,有时我在“anotherExample”等之前得到“youNeedThis”,但是结构

{变量}:{值},

总是一样的。我知道我在寻找什么(即我只想读取“anotherExample”的值)。当我得到这个数字时,我希望它在单独的行中将其写入某个 txt 文件:

129

30219

从我到目前为止所得到的是将文件中的每个数字写在单独的行中,但我必须将它们过滤掉以仅包含我正在寻找的那些。有没有办法过滤掉这个而不必做这样的事情:

$c = 0;
if (fread($file, 1) == "a" && $c == 0) $c++;
if (fread($file, 1) == "n" && $c == 1) $c++;
if (fread($file, 1) == "o" && $c == 2) $c++;
// And here after I check if this is correct line, I take the number and write the rest of it to output.txt
4

3 回答 3

2

发现正则表达式

preg_match_all('/anotherExample\:\s*([0-9]+)/sm', file_get_contents('input.txt'), $rgMatches);
file_put_contents('output.txt', join(PHP_EOL, $rgMatches[1]));
于 2013-08-16T12:56:05.377 回答
1

像这样的东西怎么样:

<?php

$data = file_get_contents($filename);
$entries = explode(",", $data);
foreach($entries as $entry) {
    if(strpos($entry, "anotherExample") === 0) {
        //Split the entry into label and value, then print the value.
    }
}

?>

您可能想做一些比explodeto get更健壮的$entries事情,例如preg_split.

于 2013-08-16T12:56:23.520 回答
0

我已经解决了这个问题:

$fileHandlerInput = file_get_contents($fileNameInput);
$rows = explode (",", $fileHandlerInput);

foreach($rows as $row) {
    $output = explode(":", $row);
    if (preg_match($txtTemplate, trim($output[0]))) {
        fwrite($fileHandlerOutput[0], trim($output[1])."\r");
    }
}    

它不是最有效也不是最整洁的,但它有效,两个答案都帮助我弄清楚了这一点。

于 2013-08-16T13:38:55.617 回答