所以我有一个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');
$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-用户A信息:你好
时间:2014年12月31日11世界卫生组织:56-用户B信息:你好
这接近于我想要的,但正如你所看到的,因为我使用了分隔符":"它还将缩短时间,并将分钟放在"谁"中。我怎么能只在第二个":"时爆炸?
我希望这有道理?
了解的工作原理
<?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 />';
}
?>