-1

我正在制作一个 PHP 刮板,并有以下代码通过查看 span 来从页面中获取标题uiButtonText。但是我现在想扫描一个超链接并让它 pregmatch <a href="*" class="thelink" onclick="*">(.*)</a>

我想成为通配符的星星,这样即使href和onclick每个都发生变化,我也可以从页面中获取超链接。

if (preg_match("/<span class=\"uiButtonText\">(.*)<\/span>/i", $cache, $matches)){print($matches[1] . "\n");}else {}

我的完整代码:

<?php
$userAgent = 'Googlebot/2.1 (http://www.googlebot.com/bot.html)';
$url = "http://www.facebook.com/MauiNuiBotanicalGardens/info";
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_AUTOREFERER, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$html = curl_exec($ch);
$cache = $html;

if (preg_match("/<span class=\"uiButtonText\">(.*)<\/span>/i", $cache, $matches))    {print($matches[1] . "\n");}else {}
?>`
4

1 回答 1

0

如果你想坚持你的正则表达式,试试这个:

$html = '<span class="uiButtonText"><a href="http://google.com" class="thelink" onclick="#">Google!</a></span>';

preg_match("/<span class=\"uiButtonText\"><a href=\".*\" class=\"thelink\" onclick=\".*\">(.*)<\/a><\/span>/i", $html, $matches);

print_r($matches[1]);

输出:
谷歌!

更好的方法是使用PHP Simple HTML DOM Parser并执行以下操作:

$html = file_get_html("http://www.facebook.com/MauiNuiBotanicalGardens/info");
foreach($html->find("a.thelink") as $link){
    echo $link->innertext . "<BR>";
}

以上未经测试,但应该可以工作

于 2013-03-23T02:34:35.927 回答