【问题标题】:how to remove class from preg_match and how to create timestamp如何从 preg_match 中删除类以及如何创建时间戳
【发布时间】:2020-11-05 23:19:00
【问题描述】:

我正在尝试获取 2020-11-05 20:34:38 此数据并将其转换为时间戳,请帮助

谢谢你

<?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

我正在尝试获取 2020-11-05 20:34:38 此数据并将其转换为时间戳,请帮助

谢谢

【问题讨论】:

  • 你忘了在去&gt;的路上有class="time"preg_match('/&lt;time datetime="(.*?)"[^&gt;]*&gt;[0-9:]+&lt;\/time&gt;/i', $html, $d ) 可以使用,请参阅 3v4l.org/q57I8

标签: php regex preg-match preg-match-all


【解决方案1】:

time标签中修剪date,如果你确定日期时间的类型,你可以试试这个:

<?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);

输出

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

如果您不确定 datetime 属性中的内容,那么您更喜欢以如下模式编写正则表达式:

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

为了得到时间戳:

echo(strtotime($date)); 

输出

1604608478

【讨论】:

    【解决方案2】:

    将您的模式更改为/datetime="([^"]+)/

    <?php
    $html = '<time datetime="2020-11-05T20:34:38+00:00" class="time">20:34</time></a></span>';
    preg_match('/datetime="([^"]+)/i', $html, $d );
    print_r($d[1]);
    

    【讨论】:

      【解决方案3】:

      你应该在正则表达式中添加class,就像这个例子:

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

      【讨论】:

        猜你喜欢
        • 2012-06-28
        • 1970-01-01
        • 1970-01-01
        • 2013-12-03
        • 1970-01-01
        • 2020-06-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多