简体   繁体   English

Preg匹配2个字符串之间的任何东西

[英]Preg Match anything between 2 strings

I have to get the location of a number from this site 我必须从该站点获取号码的位置

lookupexpert.com/search_phone?phone_number=7322691678 lookupexpert.com/search_phone?phone_number=7322691678

And i want a regex that matches anything inside 我想要一个正则表达式匹配里面的任何东西

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

How do i do that? 我怎么做?

This is what i did so far 这是我到目前为止所做的

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

?>

and also ... i tried with Xpath, and didn't worked so good, because it is not properly validated 而且...我尝试使用Xpath,但效果不佳,因为未正确验证

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

Try this: 尝试这个:

$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]);

This outputs: 这输出:

string(14) "OCEAN GATE, NJ" 

Demo 演示

Use this XPath 使用这个XPath

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

or this RegEx 或此RegEx

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

code

preg_match_all('%(?<=<p class="location">)([^<>]+)(?=</p>)%', $subject, $result, PREG_PATTERN_ORDER);
$result = $result[1];

Try this one.. 试试这个

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

$preg = preg_match_all($pattern, $string, $match);
print_r($match);

Better not to rely on unreliable regex parsing the HTML and use a DOM parser instead. 最好不要依赖于不可靠的正则表达式来解析HTML,而应使用DOM解析器。 Use a code like this: 使用如下代码:

$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

OUTPUT: OUTPUT:

Location Name: [OCEAN GATE, NJ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM