Rtra Rtra - 3 years ago 204
PHP Question

PHP preg_match extract date/time inside <td> and convert into Unix time

In my code I am trying to extract date/time only from

<td>
and then want to convert it into Unix time-stamp but I am stuck at extracting
preg_match_all()
function it won't show anything when I use
$result[0]
or
$result[1]
. I don't know why but when I dump the array I got following result:

My Array

Array
(
[0] => Array
(
[0] => <td align="left" valign="top">02 April 2017 | 05:55 PM</td>
)

[1] => Array
(
[0] => 02 April 2017 | 05:55 PM
)

)


Here is my PHP code

preg_match_all('/<td align="left" valign="top">([^"]*)<\/td>/', $printtable, $result);
var_dump($result);

Answer Source

preg_match_all returns a multidimensional array, not a single element array like preg_match. Your capture group is $result[1][0] (the 1 index is the first capture group, all other indices are additional capture groups). To convert the string to unix time you can use strtotime with str_replace (to get it to a format strtotime can handle, you also could use preg_replace and strip all non alphanumerical/space characters).

echo strtotime(str_replace('|', '', '02 April 2017 | 05:55 PM'));

Demo: https://3v4l.org/MsOlv

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download