Question

I have this text file:

Dec 04 20:15 Naruto 123
Dec 04 17:42 Naruto 98
Dec 04 16:19 D Gray Man 001
Dec 04 16:05 Bleach 128
Dec 04 12:13 50 x 50 44

I need to output the contents into a table with the Date and Time in its own column and the Tile and Chapter in another.

Also.. I need to replace the Title and Chapter with a link that must be formatted this way:

<a href="/title/title chapter">title chapter</a>

For clarification the titles in the text file are:

Naruto
Naruto
D Gray Man
Bleach
50 x 50

And the chapters are the numbers that follow:

123
98
001
128
44
Was it helpful?

Solution

  1. Read the file and store each line into an array.
  2. Open <table> tag
  3. Loop through the array and extract the date/time/title/chapter using regex.

Here is the regex to start with - you might want to modify it a little to meet your needs:

/^([a-zA-Z]{3}\s\d{2})\s(\d{2}:\d{2})\s(.+?)\s(\d+)\s*?$/
//$1 contains date : "Dec 04"
//$2 contains time : "20:15"
//$3 contains the title : "Naruto"
//$4 contains the chapter : "123"

For each item in the array, write appropriate <tr> & <td> tags filled with the extracted data.

Update:

<?php
$filedata = "Dec 04 20:15 Naruto 123
Dec 04 17:42 Naruto 98
Dec 04 16:19 D Gray Man 001
Dec 04 16:05 Bleach 128
Dec 04 12:13 50 x 50 44";

$lines = explode("\n", $filedata);

echo "<table border=\"1\">";

foreach($lines as $line)
{
    echo "<tr>";
    preg_match("/^([a-zA-Z]{3}\s\d{2}\s\d{2}:\d{2})\s(.+?)\s(\d+)\s*?$/", $line, $matches);
    echo "<td>$matches[1]</td>";
    echo "<td><a href=\"/$matches[2]/$matches[2] $matches[3]\">$matches[2] $matches[3]</a></td>";
    echo "</tr>";
}
echo "</table>"
?>

OTHER TIPS

Something like this should do the trick (haven't tested the code):

$data = Explode ( "\n", File_Get_Contents ( 'yourfile' ) );

foreach ( $data as $key => $line )
{
    $tmp = Explode ( ' ', $line );
    $month = $tmp[0];
    $day = $tmp[1];
    $time = $tmp[2];
    $numOfEntries = Count ( $tmp );
    $chapter = $tmp[$numOfEntries - 1];

    $title = '';
    for ( $i = 3; $i < $numOfEntries - 1; $i++ )
        $title .= $tmp[$i] . ' ';

    $title = Trim ( $title );

    $link = '<a href="/' . $title . '/' . $title . ' ' . $chapter . '">' . $title . ' ' . $chapter . '</a>';
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top