我正在尝试使用curl从网上获取一些数据。我所拥有的是一个像somewebsite.com
这样的网址。在这个网站上,有一大堆<divs>
有一个class="control-element"
并且有这个标记:
<div class="control-element">
<a href="http://someurl.com/and/some/path">Anchor Text</a>
</div>
我应该如何提取每个链接的网址和锚文本?我应该使用正则表达式吗?或者最好的方法是什么?
答案 0 :(得分:1)
我认为在这种特殊情况下,您可以使用 file_get_contents() 代替 cURL 。
对于html解析,请查看 Simple HTML DOM 。
如果您不想使用任何第三方库,以下是使用正则表达式的示例:
$doc = file_get_contents("http://someurl.com/");
preg_match_all('/<div class="control-element">(.*)<\/div>/isU', $doc, $matches);
$co = count($matches[1]);
for($i = 0; $i<$co;$i++)
{
preg_match_all('/<a href="(.*)">(.*)<\/a>/isU', $matches[1][$i], $matches2);
echo("URL: ".$matches2[1][0]." Anchor: ".$matches2[2][0]."<br>");
}