如何只显示带有关键字的文件中的确切行?

时间:2015-04-07 16:18:27

标签: php fopen fread

我正在寻找一种方法,只能借助文件中的关键字显示某些字符串。因此,例如,如果有人在文本字段中输入某个玩家名称,则只会从日志文件中显示该玩家所执行的命令。

日志文件

Command: .gm fly on [Player: PlayerOne (Guid: 135) (Account: 256) X: 16222.640625 Y: 16253.207031 Z: 12.735716 Map: 720 (Realmlist) Area: 0 (Unknown) Zone: Unknown Selected none: (GUID: 0)]
Command: .gm on [Player: PlayerTwo (Guid: 136) (Account: 257) X: 16252.911133 Y: 16232.371094 Z: 30.036341 Map: 720 (Realmlist) Area: 0 (Unknown) Zone: Unknown Selected none: (GUID: 0)]
Command: .mod sp 5 [Player: PlayerThree (Guid: 137) (Account: 258) X: 16252.911133 Y: 16232.371094 Z: 30.036341 Map: 720 (Realmlist) Area: 0 (Unknown) Zone: Unknown Selected none: (GUID: 0)]
到目前为止

PHP脚本

它现在只转储整个GM.log文件。

$logfile = "/logs/GM.log"; // Directory where the GM.log is stored.

$file = fopen($logfile, "r") or die("Unable to open file!");

$read = fread($file,filesize($logfile));

    echo nl2br($read); //Dump the whole file for now.

fclose($file);

我并不是要求有人为我编写确切的代码,而是要求我提示如何以最佳方式进行操作。

1 个答案:

答案 0 :(得分:1)

这样的事情对你有用:

只需通过file()将您的文件转换为数组即可。然后使用preg_grep()来识别您想要的行。

<?php

    $lines = file("logs.txt");
    $lines = preg_grep("/Player: PlayerTwo/", $lines);
    print_r($lines);

?>

输出:

Array ( [1] => Command: .gm on [Player: PlayerTwo (Guid: 136) (Account: 257) X: 16252.911133 Y: 16232.371094 Z: 30.036341 Map: 720 (Realmlist) Area: 0 (Unknown) Zone: Unknown Selected none: (GUID: 0)] )