【问题标题】:PHP - Scraping a DIV Element from a Web Page using preg_matchPHP - 使用 preg_match 从网页中抓取 DIV 元素
【发布时间】:2017-06-22 00:40:11
【问题描述】:

我目前正在尝试使用 preg_match 来检索 1 个值(在我开始检索多个值之前),但是,我没有运气。当我执行 print_r() 时,我的数组中没有存储任何内容。

这是我目前正在尝试的代码:

<?php
$content = '<div class="text-right font-90 text-default text-light last-updated vertical-offset-20">
    Reported ETA Received:
    <time datetime="2017-02-02 18:12">2017-02-02 18:12</time>
    UTC
</div>';
preg_match('|Reported ETA Received: <time datetime=".+">(.*)</time>(.*)\(<span title=".+">(.*)<time datetime=".+">(.*)</time></span>\)|', $content, $reported_eta_received);

if ($reported_eta_received) {
    $arr_parsed['reported_eta_received'] = $reported_eta_received[1];
}
?>

所需输出:

2017-02-02 18:12

我的上述代码不起作用。在这方面的任何帮助将不胜感激。提前致谢。

【问题讨论】:

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


【解决方案1】:

它可能不匹配,因为 Reported ETA Received: 和 &lt;time&gt; 标记之间有一个新行。而且您刚刚在其中放置了一个空格(使用 [\n\r\s\t]+ 而不是 " ")。

另外,你为什么不简单地使用:

preg_match('|&lt;time datetime=".*?"&gt;(.*?)&lt;/time&gt;|', $content, $reported_eta_received);

您还可以使用:?P&lt;name&gt; 来更轻松地指向(关联与数字:如果您放置更多捕获组,数字会发生变化)。

preg_match('|<time datetime=".*?">(?P<name>.*?)</time>|', $content, $match); print_r($match); // $match['name'] should be there if matched.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-27
    • 2021-03-25
    相关资源
    最近更新 更多