Reputation: 133
I have to write a parser for a txt file with structure like this:
exampleOfSomething: 95428, anotherExample: 129, youNeedThis: 491,\n
anotherExample: 30219, exampleOfSomething: 4998, youNeedThis: 492,
But there is one major problem - like in the example - the file doesn't always come out in one order, sometimes i get "youNeedThis" before "anotherExample" etc., but the structure
{variable}: {value},
is always the same. I know what I'm looking for (i.e. I want to read only the value of "anotherExample"). When I get this number I want it to write it to some txt file in separate lines:
129
30219
From what I've gotten so far is to write every number from the file in separate line, but I have to filter them out to only contain the ones I'm looking for. Is there a way of filtering this out without having to do something like this:
$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
Upvotes: 0
Views: 89
Reputation: 133
I've solved it with this:
$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");
}
}
It's not the most efficient nor neat one but it works, both answers helped me with figuring this out.
Upvotes: 0
Reputation: 9967
How about something like this:
<?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.
}
}
?>
You'll probably want to do something a little more robust than just an explode
to get $entries
, something like preg_split
.
Upvotes: 1
Reputation: 37365
Discover regular expressions.
preg_match_all('/anotherExample\:\s*([0-9]+)/sm', file_get_contents('input.txt'), $rgMatches);
file_put_contents('output.txt', join(PHP_EOL, $rgMatches[1]));
Upvotes: 2