-1

私はPHPスクレーパーを作成しており、スパン内を見てページからタイトルを取得する次のコードがあります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]);

出力:
Google!

より良い方法は、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 に答える