在HTML文档中搜索facebook页面URL和twitter URL


Search an HTML document for facebook page URL and twitter URL

我正在从一些网站抓取数据,所以在响应HTML代码中,我想获取facebook页面链接和twitter帐户链接(如果有的话)。获取的一个html代码示例如下:注意:我使用CURL模块来获取数据。

<a href="https://www.facebook.com/Example-page-16149277784545354/" target="_blank">
<div class="template asset" data-id="4722053" contenteditable="false">
<figure>
........
</figure>
</div>
</a>

我需要"href"属性中的facebook页面链接,twitter帐户链接也是如此。

我还没有测试过这个代码。但这是一个粗略的解决方法,这个循环可能会无限。请测试并更正错误。

<?php
$str = file_get_contents($url);
$i = -1;
while(strpos("href='",$i)>=0){
   $strpos = strpos("href='",$i);
   $i2 = strpos("'",$i+7);
   $link = substr($str,$strpos,$i2);
   $i = $i2 + 1;
  //now check if the link is facebook, twitter etc.
}
//do the same with while(strpos("href='"",$i)>=0){

您可以使用regex进行检查,下面是一个facebook检查示例:

$testString = '<a href="https://www.facebook.com/Example-page-16149277784545354/" target="_blank">
<div class="template asset" data-id="4722053" contenteditable="false">
<figure>
........
</figure>
</div>
</a>';
$facebookPattern = '/"(http[s]{0,1}:'/'/www'.facebook'.com[^"]+)"/';
preg_match_all($facebookPattern, $testString, $matches);
print_r($matches[1]);

另请参阅https://regex101.com/r/sW7eV1/1

您可以使用简单的html dom,它提供了一个面向对象的接口。您只需向获取html并将其解析为对象的函数提供url即可。您可以调用该对象的属性和方法来访问dom的元素。

供参考:http://simplehtmldom.sourceforge.net/manual.htm