我必须从该站点获取号码的位置

lookupexpert.com/search_phone?phone_number=7322691678

我想要一个匹配里面任何东西的正则表达式

<p class="location">OCEAN GATE, NJ</p>


我怎么做?

这是我到目前为止所做的

<?php

$subject = file_get_contents("http://lookupexpert.com/search_phone?phone_number=7322691678");

$pattern = '#\<p class="location"\>(.+?)\<\/p\>#s';
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3);
print_r($matches);

?>


而且...我尝试使用Xpath,但效果不佳,因为未正确验证

/html/body/div/div[2]/div/ul/li[2]/p[4]

最佳答案

最好不要依赖于不可靠的正则表达式来解析HTML,而应使用DOM解析器。使用如下代码:

$doc = new DOMDocument();
libxml_use_internal_errors(true);
// assuming search_phone.html contains your saved HTML source
#$doc->loadHTMLFile('search_phone.html'); // loads your html
$xpath = new DOMXPath($doc);
$value = $xpath->evaluate("string(//li[starts-with(@class, 'recordItem')]/
                           p[@class='location']/text())");
echo "Location Name: [$value]\n"; // prints your location


输出:

Location Name: [OCEAN GATE, NJ]

关于php - Preg匹配2个字符串之间的任何东西,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10852409/

10-13 00:40