1

我正在尝试解析文本文件,但我不确定这样做的最佳方法和做法。使用 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

 =>
4

1 回答 1

2

示例如何在 PHP 中使用正则表达式获取日期、时间和温度

<?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;
}

?>
于 2013-07-09T00:17:13.743 回答