2

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

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]
4

4 回答 4

4

尝试这个:

$subject = file_get_contents( 'http://www.lookupexpert.com/search_phone?phone_number=7322691678');
preg_match_all( '#<p class="location">(.*?)</p>#', $subject, $matches);
var_dump( $matches[1][1]);

这输出:

string(14) "OCEAN GATE, NJ" 

演示

于 2012-06-01T14:52:46.560 回答
2

使用这个 XPath

//p[@class='location']/text()

或这个正则表达式

(?<=<p class="location">)([^<>]+)(?=</p>)

代码

preg_match_all('%(?<=<p class="location">)([^<>]+)(?=</p>)%', $subject, $result, PREG_PATTERN_ORDER);
$result = $result[1];
于 2012-06-01T14:56:15.020 回答
1

试试这个。。

$string = '<p class="location">OCEAN GATE, NJ</p>';
$pattern = '/<p class="location">(.*)<\/p>/';

$preg = preg_match_all($pattern, $string, $match);
print_r($match);
于 2012-06-01T14:50:17.673 回答
1

最好不要依赖不可靠的正则表达式来解析 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]
于 2012-06-01T15:00:03.343 回答