Question

I have outside HTML file, that I read to PHP variable. In this HTML file there are different dates(and times). What would be the easiest way to read them to variable. Date-time is always in the following format: <td align="left" valign="middle" class="contentValueFont">01-Mar-14 19:24:45 GMT</td>
Ofcourse date and time change.
In other place I used to search with class name and read all the following to variable until </td> comes, but this time same class name is used in different places, not associated with my date/time.
I am not good at regular expressions.

Thanks for help. T.

Was it helpful?

Solution 2

This might work:

preg_match('/\d\d-[A-Z]{3}-\d\d \d\d:\d\d:\d\d [A-Z]{3}/i', $html, $match);
print_r($match);

Based on your comment, this will get all of the dates of that format:

preg_match_all('/\d\d-[A-Z]{3}-\d\d \d\d:\d\d:\d\d [A-Z]{3}/i', $html, $matches);
print_r($matches[0]); 

OTHER TIPS

A regular expression is not the right tool for the job. Use an HTML parser to extract the date and DateTime class to do the processing:

$html = <<<HTML
<td align="left" valign="middle" class="contentValueFont">01-Mar-14 19:24:45 GMT</td>
HTML;

$dom = new DOMDocument;
$dom->loadHTML($html);
$date = $dom->getElementsByTagName('td')->item(0)->nodeValue;

$dateObj = new DateTime($date);
echo $dateObj->format('Y-m-d H:i:s');

Output:

2014-03-01 19:24:45

You will need to use regular expressions (very little), but php provides this function for exactly your needs.

<?php

$unix = strtotime('01-Mar-14 19:24:45 GMT'); //get unix timestamp
echo date('d-M-y H:i:s', $unix); // output in any format
//output - 01-Mar-14 19:24:45

Reference to all character that can be used in date() for formatting: http://in1.php.net/manual/en/function.date.php

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top