我正在尝试解析文本文件,但我不确定这样做的最佳方法和做法。使用PHP我想将整个文件加载到字符串中还是应该逐行进行?我很熟悉JavaScript方法,也不熟悉!
我应该使用strstr搜索大海捞针内的针头吗?或者其他什么方法适合解析一致的简单文本文件。
请注意,我想要的唯一数据是文本文件(temp_log.txt):
Date: 07/07/2013 Time: 00:57:00.208 21 C
Date: 07/07/2013 Time: 00:57:02.029 25 C
temp_log.txt:
=>MET RTD
SEL-2411 Date: 07/07/2013 Time: 00:57:00.208
DEVICE
INTRTD01 21 C
INTRTD02 Open
INTRTD03 Open
INTRTD04 NA
INTRTD05 NA
INTRTD06 NA
INTRTD07 NA
INTRTD08 NA
INTRTD09 NA
INTRTD10 NA
=>
=>MET RTD
SEL-2411 Date: 07/07/2013 Time: 00:57:02.029
DEVICE
INTRTD01 25 C
INTRTD02 Open
INTRTD03 Open
INTRTD04 NA
INTRTD05 NA
INTRTD06 NA
INTRTD07 NA
INTRTD08 NA
INTRTD09 NA
INTRTD10 NA
=>
答案 0 :(得分:2)
如何使用PHP中的ReGex获取日期和时间以及温度
<?php
$text =
"=>MET RTD
SEL-2411 Date: 07/07/2013 Time: 00:57:00.208
DEVICE
INTRTD01 21 C
INTRTD02 Open
INTRTD03 Open
INTRTD04 NA
INTRTD05 NA
INTRTD06 NA
INTRTD07 NA
INTRTD08 NA
INTRTD09 NA
INTRTD10 NA
=>
=>MET RTD
SEL-2411 Date: 07/07/2013 Time: 00:57:02.029
DEVICE
INTRTD01 25 C
INTRTD02 Open
INTRTD03 Open
INTRTD04 NA
INTRTD05 NA
INTRTD06 NA
INTRTD07 NA
INTRTD08 NA
INTRTD09 NA
INTRTD10 NA
=>";
// split text to lines
$lines = explode("\n", $text);
// find date, time and temperature
$all = array();
$date = "";
$time = "";
foreach( $lines as $line ) {
$number = preg_match('#Date: ([^ ]+).*Time: ([^ ]+)#', $line, $result);
if( $number > 0 ) {
$date = $result[1];
$time = $result[2];
}
$number = preg_match('# (\d+) C#', $line, $result);
if( $number > 0 ) {
$all[] = array($date, $time, $result[1]);
}
}
// print all results
foreach($all as $element) {
echo "Date: ", $element[0], " Time: ", $element[1], " ", $element[2], " C", PHP_EOL;
}
?>