获取指定文本 PHP 之间的字符串



我正在尝试从中提取日期和时间,我将如何去做?

我的代码

    <?php
$url = file_get_contents('http://webcache.googleusercontent.com/search?q=cache:http://unitedseo.ae');
    $doc = new DOMDocument();
    $doc->loadHTML($url);
    $node = $doc->getElementById('google-cache-hdr');
    echo $doc->saveHtml($node), PHP_EOL;
?>

我的代码返回这个

<body><div id="google-cache-hdr" dir="ltr">
<div>This is Google's cache of <a href="http://www.unitedseo.ae/" dir="ltr">http://www.unitedseo.ae/</a>. It is a snapshot of the page as it appeared on May 20, 2017 05:16:23 GMT. </div>
<div>The <a href="http://www.unitedseo.ae/" dir="ltr">current page</a> could have changed in the meantime. <a href="http://support.google.com/websearch/bin/answer.py?hl=en&amp;p=cached&amp;answer=1687222">Learn more</a>
</div>
<div></div>
<div>
<span style="display:inline-block !important;margin-top:8px !important;margin-right:104px !important;white-space:nowrap !important;"><span style="margin-right:28px !important;"><span style="font-weight:bold !important;">Full version</span></span><span style="margin-right:28px !important;"><a href="http://webcache.googleusercontent.com/search?q=cache:http://unitedseo.ae&amp;num=1&amp;ie=UTF-8&amp;prmd=ivns&amp;strip=1&amp;vwsrc=0">Text-only version</a></span><span style="margin-right:28px !important;"><a href="http://webcache.googleusercontent.com/search?q=cache:http://unitedseo.ae&amp;num=1&amp;ie=UTF-8&amp;prmd=ivns&amp;strip=0&amp;vwsrc=1">View source</a></span></span><span style="display:inline-block !important;margin-top:8px !important;color:#717171 !important;">Tip: To quickly find your search term on this page, press <b>Ctrl+F</b> or <b>⌘-F</b> (Mac) and use the find bar.</span>
</div>
</div>
</body>

希望这会有所帮助。

<?php
ini_set('display_errors', 1);
libxml_use_internal_errors(true);
$url = file_get_contents('http://webcache.googleusercontent.com/search?q=cache:http://unitedseo.ae');
$doc = new DOMDocument();
$doc->loadHTML($url);
$node = $doc->getElementById('google-cache-hdr');
$results = $doc->saveHtml($node);
preg_match("#d{1,2}s[a-zA-Z]{3}sd{4}sd{2}:d{2}:d{2}#", $results, $matches);
print_r($matches);

输出:

Array
(
    [0] => 20 May 2017 05:16:23
)

则表达式可能是最好的解决方案,但我也可以尝试strpos方法。

如果您要搜索文本appeared on,获取位置,然后搜索位置.</div>您可以找到时间的位置并提取它。

未测试

<?php
    $url = file_get_contents('http://webcache.googleusercontent.com/search?q=cache:http://unitedseo.ae');
    $doc = new DOMDocument();
    $doc->loadHTML($url);
    $node = $doc->getElementById('google-cache-hdr');
    echo $rs = $doc->saveHtml($node);
    preg_match('/(d?d [A-Za-z]+ dddd) (dd:dd)/', $rs, $matches);
    echo $matches[0];
    print_r($matches);die;
    die;
?>

最新更新