从文本文件中提取某些数据并创建 table

Extract certain data from a text file and create a table

您好,我是 PHP 编程的新手,我只是想学习更多关于如何使用文件的知识。

我有一个文本文件,其中包含如下所示的一些数据。

image from the file

Policy Name:       TU_TOPS_VM-Full_30D_00_2
  Daily Windows:
         Saturday   19:50:00  -->  Sunday     06:00:00
Policy Name:       TU_QW_VM-FULL_30D_18_01
    Daily Windows:
          Sunday 02:05:00 --> Sunday 09:00:00
Policy Name:       TU_GPAS_FULL-VM_30D_18_01
    Daily Windows:
          Friday     22:00:00  -->  Saturday   06:00:00

我想在 table.

中得到与此类似的输出
POlicy                               Day              Time
TU_TOPS_VM-Full_30D_00_2 Saturday    Saturday         19:50:00
TU_QW_VM-FULL_30D_18_01              Sunday           02:05:00
TU_GPAS_FULL-VM_30D_18_01            Friday           22:00:00

从我的代码中,我能够获取策略名称并将数据组织在 table 列中。

代码输出。

POlicy                        Day     Time
TU_TOPS_VM-Full_30D_00_2
TU_QW_VM-FULL_30D_18_01

到目前为止我能做什么。

<?php
$lines= file('schedule');
$lines = preg_grep("/Policy Name:/", $lines);
echo'
<table>
<tr>
<td>POlicy</td>
<td>Day</td>
<td>Time</td>
</tr>';
foreach ($lines as $policy) {
$find="Policy Name:";
$replace="";
$po= (str_replace($find,$replace,$policy));
echo '
<tr>
<td>'.$po.'<br></td>
</tr>
</table>';
}
?>

我如何提取日期和时间并在策略旁边进行组织 姓名?.

当您使用 preg_grep 时,您将丢弃其他行。相反,遍历所有行,检查它是哪一种行。

此外,</table>不应该在循环内部,它应该只在循环的末尾。

<?php
$lines= file('schedule', FILE_IGNORE_NEW_LINE);
echo'
<table>
<tr>
<td>POlicy</td>
<td>Day</td>
<td>Time</td>
</tr>';
foreach ($lines as $line) {
    if (strstr($line, 'Policy Name:')) {
        $policy = str_replace('Policy Name:', '', $line);
    } elseif (preg_match('/(\w+)\s+(\d\d:\d\d:\d\d)\s+-->/', $line, $match)) {
        $day = $match[1];
        $time = $match[2];
    echo "
<tr>
<td>$policy</td>
<td>$day</td>
<td>$time</td>
</tr>";
    }
}
echo "\n</table>";
?>

@Barmar 写了一个很好的答案。这是一个不同的策略,因为我想控制我的数组中断的位置(即不在每一行,因为我不确定你的换行​​符在哪里)。此外,不太具体的匹配为您提供了更多支持输入的可变性(这对您来说可能不是问题)。

<?php    
$string = file_get_contents('schedule') ; // read the file in as a string, not an array              
$text_array = explode("Policy Name:", $string) ; // break the string into an array of strings at each "Policy Name:"

foreach($text_array as $entry){
        $entry = preg_replace('/\s+/', ' ',$entry) ; // conflate whitespace into a single space for delimiting
        $sub_entry_array = explode(' ', $entry) ; // split each substring into an array
        $table_rows .= "<tr><td>$sub_entry_array[1]</td><td>$sub_entry_array[4]</td><td>$sub_entry_array[5]</td></tr>" ; // display the array values we want
}

echo "<table><tr><th>Policy</th><th>Day</th><th>Time</th></tr>$table_rows</table>" ;
?>