PHP文章採集URL補全函數(FormatUrl)_PHP教程

來源:互聯網
上載者:User
寫採集必用的函數,URL補全函數,也可叫做FormatUrl。
寫此函數作用就是為了開發採集程式,採集文章的時候會經常遇到頁面裡的路徑是 “相對路徑” 或者 “絕對根路徑” 不是“絕對全路徑”就無法收集URL。

所以,就需要本功能函數進行對代碼進行格式化,把所有的超連結都格式化一遍,這樣就可以直接收集到正確的URL了。

路徑知識普及
相對路徑:“../” “./” 或者前面什麼都不加
絕對根路徑:/path/xxx.html
絕對全路徑:http://www.xxx.com/path/xxx.html
使用執行個體:
複製代碼 代碼如下:
$surl="http://www.jb51.net/";
$gethtm = '首頁解決方案';
echo formaturl($gethtm,$surl);
?>

輸出:首頁解決方案
--------- 示範執行個體 ------------
原始路徑代碼:http://www.newnew.cn/newnewindex.aspx
輸出示範代碼:http://www.maifp.com/aaa/test.php
以下是函數代碼
複製代碼 代碼如下:
function formaturl($l1,$l2){
if (preg_match_all("/(]+src=\"([^\"]+)\"[^>]*>)|(]+href=\"([^\"]+)\"[^>]*>)|(]+src='([^']+)'[^>]*>)|(]+href='([^']+)'[^>]*>)/i",$l1,$regs)){
foreach($regs[0] as $num => $url){
$l1 = str_replace($url,lIIIIl($url,$l2),$l1);
}
}
return $l1;
}
function lIIIIl($l1,$l2){
if(preg_match("/(.*)(href|src)\=(.+?)( |\/\>|\>).*/i",$l1,$regs)){$I2 = $regs[3];}
if(strlen($I2)>0){
$I1 = str_replace(chr(34),"",$I2);
$I1 = str_replace(chr(39),"",$I1);
}else{return $l1;}
$url_parsed = parse_url($l2);
$scheme = $url_parsed["scheme"];if($scheme!=""){$scheme = $scheme."://";}
$host = $url_parsed["host"];
$l3 = $scheme.$host;
if(strlen($l3)==0){return $l1;}
$path = dirname($url_parsed["path"]);if($path[0]=="\\"){$path="";}
$pos = strpos($I1,"#");
if($pos>0) $I1 = substr($I1,0,$pos);
//判斷類型
if(preg_match("/^(http|https|ftp):(\/\/|\\\\)(([\w\/\\\+\-~`@:%])+\.)+([\w\/\\\.\=\?\+\-~`@\':!%#]|(&)|&)+/i",$I1)){return $l1; }//http開頭的url類型要跳過
elseif($I1[0]=="/"){$I1 = $l3.$I1;}//絕對路徑
elseif(substr($I1,0,3)=="../"){//相對路徑
while(substr($I1,0,3)=="../"){
$I1 = substr($I1,strlen($I1)-(strlen($I1)-3),strlen($I1)-3);
if(strlen($path)>0){
$path = dirname($path);
}
}
$I1 = $l3.$path."/".$I1;
}
elseif(substr($I1,0,2)=="./"){
$I1 = $l3.$path.substr($I1,strlen($I1)-(strlen($I1)-1),strlen($I1)-1);
}
elseif(strtolower(substr($I1,0,7))=="mailto:"||strtolower(substr($I1,0,11))=="javascript:"){
return $l1;
}else{
$I1 = $l3.$path."/".$I1;
}
return str_replace($I2,"\"$I1\"",$l1);
}
?>

下面的連結是學習PHPRegex的地方。在這裡留個連結,防止丟失。。。

http://www.bkjia.com/PHPjc/325775.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/325775.htmlTechArticle寫採集必用的函數,URL補全函數,也可叫做FormatUrl。 寫此函數作用就是為了開發採集程式,採集文章的時候會經常遇到頁面裡的路徑是 “相...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.