您能帮我解决这个问题吗? 我有一个日志文件,里面有列。我只想读一列。
这是示例日志文件:
2019-05-14 00:00:00 1558449 v7.41 33309
2019-05-14 00:00:00 1335564 v7.38 33600
2019-05-14 00:00:00 1584141 v7.34 39800
2019-05-14 00:00:00 1556654 v7.38 33600
2019-05-14 00:00:00 1456993 v7.39 33600
2019-05-14 00:00:00 1581138 v7.39 33600
2019-05-14 00:00:00 1224055 v7.39 33600
2019-05-14 00:00:00 1557900 v7.35 33309
2019-05-14 00:00:00 1576229 v7.39 33600
2019-05-14 00:00:00 1553292 v7.35 33309
我只需要阅读1558449列即可。
我尝试过的代码在此链接中:
https://www.quora.com/How-do-I-to-read-lines-from-text-file-into-a-table-format-in-PHP
我希望输出将像这样:
1558449
1335564
1584141
1556654
1456993
1581138
1224055
1557900
1576229
1553292
答案 0 :(得分:1)
嘿,用正则表达式解决它。
首先,使用PHP的file_get_contents()
函数读取文件。此函数将整个文件读取为字符串。
Reads entire file into a string - PHP
现在使用PHP preg_match_all()
函数,从字符串中获取所需的任何内容。
PHP: preg_match_all - Manual
请参阅:
/**
$file = "2019-05-14 00:00:00 1558449 v7.41 33309
2019-05-14 00:00:00 1335564 v7.38 33600
2019-05-14 00:00:00 1584141 v7.34 39800
2019-05-14 00:00:00 1556654 v7.38 33600
2019-05-14 00:00:00 1456993 v7.39 33600
2019-05-14 00:00:00 1581138 v7.39 33600
2019-05-14 00:00:00 1224055 v7.39 33600
2019-05-14 00:00:00 1557900 v7.35 33309
2019-05-14 00:00:00 1576229 v7.39 33600
2019-05-14 00:00:00 1553292 v7.35 33309";
*/
$file = file($addressOfFile);
preg_match_all("/.*([0-9]{7}).*/", $file, $matches);
其结果将是:
array(2) {
[0] =>
array(10) {
[0] =>
string(39) "2019-05-14 00:00:00 1558449 v7.41 33309"
[1] =>
string(39) "2019-05-14 00:00:00 1335564 v7.38 33600"
[2] =>
string(39) "2019-05-14 00:00:00 1584141 v7.34 39800"
[3] =>
string(39) "2019-05-14 00:00:00 1556654 v7.38 33600"
[4] =>
string(39) "2019-05-14 00:00:00 1456993 v7.39 33600"
[5] =>
string(39) "2019-05-14 00:00:00 1581138 v7.39 33600"
[6] =>
string(39) "2019-05-14 00:00:00 1224055 v7.39 33600"
[7] =>
string(39) "2019-05-14 00:00:00 1557900 v7.35 33309"
[8] =>
string(39) "2019-05-14 00:00:00 1576229 v7.39 33600"
[9] =>
string(39) "2019-05-14 00:00:00 1553292 v7.35 33309"
}
[1] =>
array(10) {
[0] =>
string(7) "1558449"
[1] =>
string(7) "1335564"
[2] =>
string(7) "1584141"
[3] =>
string(7) "1556654"
[4] =>
string(7) "1456993"
[5] =>
string(7) "1581138"
[6] =>
string(7) "1224055"
[7] =>
string(7) "1557900"
[8] =>
string(7) "1576229"
[9] =>
string(7) "1553292"
}
}
现在,您可以通过$matches[1]
(它是一个数组)访问所需的内容。
答案 1 :(得分:0)
您应该做的是:
示例
$fn = fopen("log.txt","r");
while(! feof($fn)) {
$line = fgets($fn);
$val = explode(" ", $line)[2];
echo $val."<br>";
}
fclose($fn);