我怎样才能只显示带有关键字的文件中的确切行?

How can I only show the exact lines from a file with a keyword?

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

日志文件

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);

我不是要别人为我编写准确的代码,我是要寻求有关如何以最佳方式做到这一点的提示。

像这样的东西应该适合你:

只需通过 file(). Then use simply 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)] )