php正則匹配擷取指定url網頁頁面超級連結地址_PHP教程

來源:互聯網
上載者:User
在資料擷取與頁面分析中,常需要抓取給定url頁面的內容,或者第二、第三層次深度頁面內容。

這裡是一個測試例子的實現,僅供參考。

代碼如下:


/*
匹配給定頁面連結
return:array match[link,content,all]
*/
function match_links($host, $document) {
$pattern = '/(.*?)/i';
preg_match_all($pattern, $document, $m);
return $m;

preg_match_all("']+))[^>]*>?(.*?)'isx",$document,$links);
while(list($key,$val) = each($links[2])) {
if(!empty($val))
if(preg_match("/http/",$val)){
$match['link'][] = $val;
}
else {
$match['link'][] = $host . $val;
}
}
while(list($key,$val) = each($links[3])) {
if(!empty($val))
if(preg_match("/http/",$val)){
$match['link'][] = $val;
}
else {
$match['link'][] = $host . $val;
}
}
while(list($key,$val) = each($links[4])) {
if(!empty($val))
$match['content'][] = $val;
}
while(list($key,$val) = each($links[0])) {
if(!empty($val))
$match['all'][] = $val;
}
return $match['link'];
}

/*
從給定url中擷取頁面常值內容
*/
function get_content_from_url($url) {
$str = @file_get_contents($url);
if(mb_check_encoding($str, "GBK"))
$str = iconv("GBK","UTF-8", $str);
$str = strip_tags($str); // 過濾html標籤
/*
$str = preg_replace( "@@is", "", $str );
$str = preg_replace( "@@is", "", $str );
$str = preg_replace( "@@is", "", $str );
$str = preg_replace( "@<(.*?)>@is", "", $str );
*/
//過濾非漢字字元
preg_match_all('/[x{4e00}-x{9fff}]+/u', $str, $matches);
$str = join(',', $matches[0]);
if(!$str)
return NULL;

return $str;
}

function get_content($url,$depth) {
if(!$url || $depth < 1)
return false;

while($depth > 1){
$str = @file_get_contents($url);
if(!$str)
return false;

$parseurl = parse_url($url);
if($parseurl['host'])
$host = $parseurl[scheme] . "://" . $parseurl['host'];

$arrlink = match_links($host,$str);
$arr_url = array_unique($arrlink);

$depth--;
foreach($arr_url as $url){
$content .= get_content($url, $depth); //遞迴調用
}
}

$content .= get_content_from_url($url);

return $content;
}

http://www.bkjia.com/PHPjc/372096.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/372096.htmlTechArticle在資料擷取與頁面分析中,常需要抓取給定url頁面的內容,或者第二、第三層次深度頁面內容。 這裡是一個測試例子的實現,僅供參考。...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.