0

次のような構造の txt ファイルのパーサーを作成する必要があります。

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

anotherExample: 30219、exampleOfSomething: 4998、youNeedThis: 492、

しかし、大きな問題が 1 つあります。例のように、ファイルが常に 1 つの順序で出力されるわけではありません。「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.
    }
}

?>

explodeおそらく、 get$entriesのようなものよりももう少し堅牢なことをしたいと思うでしょうpreg_split

于 2013-08-16T12:56:23.520 に答える