国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 開發 > PHP > 正文

PHP文章采集URL補全函數(FormatUrl)

2024-05-04 23:14:23
字體:
來源:轉載
供稿:網友
寫采集必用的函數,URL補全函數,也可叫做FormatUrl。
寫此函數作用就是為了開發采集程序,采集文章的時候會經常遇到頁面里的路徑是 “相對路徑” 或者 “絕對根路徑” 不是“絕對全路徑”就無法收集URL。

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

路徑知識普及
相對路徑:“../” “./” 或者前面什么都不加
絕對根路徑:/path/xxx.html
絕對全路徑:
使用實例:

復制代碼 代碼如下:


<?php
$surl="http://www.survivalescaperooms.com/";
$gethtm = '<a href="http://www.survivalescaperooms.com/index.htm">首頁</a><a href="Resolvent/index.htm">解決方案</a>';
echo formaturl($gethtm,$surl);
?>


輸出:<a href="http://www.survivalescaperooms.com/index.htm">首頁</a><a href="http://www.survivalescaperooms.com/Resolvent/index.htm">解決方案</a>
--------- 演示實例 ------------
原始路徑代碼:
輸出演示代碼:
以下是函數代碼

復制代碼 代碼如下:


<?php
function formaturl($l1,$l2){
if (preg_match_all("/(<img[^>]+src=/"([^/"]+)/"[^>]*>)|(<a[^>]+href=/"([^/"]+)/"[^>]*>)|(<img[^>]+src='([^']+)'[^>]*>)|(<a[^>]+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]=="http://"){$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);
}
?>


下面的鏈接是學習PHP正則表達式的地方。在這里留個鏈接,防止丟失。。。
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 巍山| 五莲县| 象州县| 博乐市| 敦煌市| 沁源县| 宜黄县| 余江县| 鹤山市| 绥阳县| 绥德县| 尼玛县| 东莞市| 炉霍县| 南江县| 大丰市| 武强县| 绵阳市| 馆陶县| 中方县| 山东| 黄山市| 西安市| 桂林市| 九龙坡区| 漳浦县| 仙居县| 井研县| 咸阳市| 贵港市| 鲁山县| 五大连池市| 米易县| 陆丰市| 邹城市| 中阳县| 宁乡县| 拉孜县| 甘孜县| 淮阳县| 禹州市|