读取文本文件PHP的某些行


Reading certain lines of a textfile PHP

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

示例:95428,另一个示例:129,你需要这个:491,''n

另一个例子:30219,例子OfSomething:498,你需要这个:492,

但有一个主要问题——就像在这个例子中一样——文件并不总是按一个顺序出现,有时我会得到";你需要这个"在";另一个例子";但是结构

{variable}:{value},

总是一样的。我知道我在寻找什么(即,我只想读取"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

发现正则表达式。

preg_match_all('/anotherExample':'s*([0-9]+)/sm', file_get_contents('input.txt'), $rgMatches);
file_put_contents('output.txt', join(PHP_EOL, $rgMatches[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更健壮的事情来获得$entries,比如preg_split

我用这个解决了这个问题:

$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");
    }
}    

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