Php 单行文本日志文件解析
因此,我有一个log/txt文件,其中包含以下内容:Php 单行文本日志文件解析,php,parsing,explode,delimiter,logfiles,Php,Parsing,Explode,Delimiter,Logfiles,因此,我有一个log/txt文件,其中包含以下内容: 31 dec. 2014 11:56 - UserA: Hi31 dec. 2014 11:56 - UserB: Hi to you31 dec. 2014 11:56 - UserA: Whats your name?31 dec. 2014 11:57 - UserB: Nancy <?php //load the logfile $txt_file = file_get_contents('test.txt'); $tx
31 dec. 2014 11:56 - UserA: Hi31 dec. 2014 11:56 - UserB: Hi to you31 dec. 2014 11:56 - UserA: Whats your name?31 dec. 2014 11:57 - UserB: Nancy
<?php
//load the logfile
$txt_file = file_get_contents('test.txt');
$txtfile2 = preg_split( "/ ( |:) /", $txt_file );
$rows = explode("\n", $txtfile2[0]);
foreach($rows as $row => $data)
{
$row_data = explode(':', $data);
$info[$row]['when'] = $row_data[0];
$info[$row]['name'] = $row_data[1];
$info[$row]['description'] = $row_data[2];
//display data
echo ' WHEN: ' . $info[$row]['when'] . '<br />';
echo ' WHO: ' . $info[$row]['name'] . '<br />';
echo ' MESSAGE: ' . $info[$row]['description'] . '<br /><br />';
}
?>
我正试图把它转换成一种更具可读性的格式。。。。。
因此,我尝试以下方法:
31 dec. 2014 11:56 - UserA: Hi31 dec. 2014 11:56 - UserB: Hi to you31 dec. 2014 11:56 - UserA: Whats your name?31 dec. 2014 11:57 - UserB: Nancy
<?php
//load the logfile
$txt_file = file_get_contents('test.txt');
$txtfile2 = preg_split( "/ ( |:) /", $txt_file );
$rows = explode("\n", $txtfile2[0]);
foreach($rows as $row => $data)
{
$row_data = explode(':', $data);
$info[$row]['when'] = $row_data[0];
$info[$row]['name'] = $row_data[1];
$info[$row]['description'] = $row_data[2];
//display data
echo ' WHEN: ' . $info[$row]['when'] . '<br />';
echo ' WHO: ' . $info[$row]['name'] . '<br />';
echo ' MESSAGE: ' . $info[$row]['description'] . '<br /><br />';
}
?>
这部分起作用了。。。。
执行时,输出为:
当:2014年12月31日11
世卫组织:56-UserA
留言:嗨
时间:2014年12月31日11
世界卫生组织:56-UserB
留言:你好
这很接近我想要的,但正如你所看到的,因为我使用了分隔符:它还将缩短时间,并将分钟放在who中。
我怎么能在第二个爆炸:只有
我希望这是有意义的?看看这对你有什么作用
<?php
$filename = "logfile.txt"; //data file to open
$fp = fopen( $filename, "r" ) or die("Couldn't open $filename");
while ( ! feof( $fp ) )
{
$line = fgets( $fp, 1024 );
$line_array = preg_split("/[:-]+/", $line);
$line_timestamp = $line_array[0] . ":" . $line_array[1];
$line_user = $line_array[2];
$line_message = $line_array[3];
echo ' WHEN: ' . $line_timestamp . '<br />';
echo ' WHO: ' . $line_user . '<br />';
echo ' MESSAGE: ' . $line_message . '<br /><br />';
}
?>
记录之间的分隔符是什么?这是一条在样本数据中没有显示的新行吗?嗯,等等,我刚刚意识到,我正在新行上进行爆炸。。。。因此,是的,每个条目后都有新行,即使它不像a/n那样显示,因为爆炸确实将其切分为正确的部分。有一种方法可以替换第一次出现的:在foreach的每次运行中,都有一个空格或一个空格。我关心的是?这个答案对你有用吗?如果我不忘的话,我会在大约4个小时后测试它,伙计!