Search code examples
phpregexpreg-matchpreg-match-all

how to remove class from preg_match and how to create timestamp


i am trying to get 2020-11-05 20:34:38 this data and convert it in timestamp please help

Thank You

<?php
$html = '<time datetime="2020-11-05T20:34:38+00:00" class="time">20:34</time></a></span>';

preg_match('/<time datetime="(.*?)">[0-9:]+<\/time>/i', $html, $d );


//print_r ($d);
print_r ($d[1]);
?>
Output

2020-11-05T20:34:38+00:00" class="time

i am trying to get 2020-11-05 20:34:38 this data and convert it in timestamp please help

Thank You


Solution

  • to trim date from time tag , if you are sure about datetime's type , you can try this:

    <?php
    $html = '<time datetime="2020-11-05T20:34:38+00:00" class="time">20:34</time></a></span>';
    $pattern = '/datetime="(?<date>\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\+\d{2}:\d{2})/';
    preg_match($pattern , $html , $matches);
    $date = $matches["date"];
    echo($date);
    

    output

    2020-11-05T20:34:38+00:00
    

    if you are not sure what is in the datetime attribute, so you prefer to write your regex in patterns like this:

    $pattern = '/datetime="(?<date>.+)\s+class/';
    

    in order to get the timestamp:

    echo(strtotime($date)); 
    

    Output

    1604608478