加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > PHP > 正文

PHP文章采集URL补全函数(FormatUrl)

发布时间:2020-05-24 17:33:34 所属栏目:PHP 来源:互联网
导读:写此函数作用就是为了开发采集程序,采集文章的时候会经常遇到页面里的路径是 相对路径 或者 绝对根路径 不是 绝对全路径 就无法收集URL

写采集必用的函数,URL补全函数,也可叫做FormatUrl。
写此函数作用就是为了开发采集程序,采集文章的时候会经常遇到页面里的路径是 “相对路径” 或者 “绝对根路径” 不是“绝对全路径”就无法收集URL。 所以,就需要本功能函数进行对代码进行格式化,把所有的超链接都格式化一遍,这样就可以直接收集到正确的URL了。 路径知识普及
相对路径:“../” “./” 或者前面什么都不加
绝对根路径:/path/xxx.html
绝对全路径:http://www.xxx.com/path/xxx.html
使用实例:
<div class="codetitle"><a style="CURSOR: pointer" data="61137" class="copybut" id="copybut61137" onclick="doCopy('code61137')"> 代码如下:<div class="codebody" id="code61137">
<?php
$surl="//www.jb51.cc/";
$gethtm = '<a href="/index.htm">首页<a href="Resolvent/index.htm">解决方案';
echo formaturl($gethtm,$surl);
?>

输出:<a href="//www.jb51.cc/index.htm">首页<a href="//www.jb51.cc/Resolvent/index.htm">解决方案
--------- 演示实例 ------------
原始路径代码:http://www.newnew.cn/newnewindex.aspx
输出演示代码:http://www.maifp.com/aaa/test.php
以下是函数代码
<div class="codetitle"><a style="CURSOR: pointer" data="52851" class="copybut" id="copybut52851" onclick="doCopy('code52851')"> 代码如下:<div class="codebody" id="code52851">
<?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",$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,$pos);
//判断类型
if(preg_match("/^(http|https|ftp):(//|)(([w/+-~@:%])+.)+([w/.=?+-~@':!%#]|(&)|&)+/i",$I1)){return $l1; }//http开头的url类型要跳过
elseif($I1[0]=="/"){$I1 = $l3.$I1;}//绝对路径
elseif(substr($I1,3)=="../"){//相对路径
while(substr($I1,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,2)=="./"){
$I1 = $l3.$path.substr($I1,strlen($I1)-(strlen($I1)-1),strlen($I1)-1);
}
elseif(strtolower(substr($I1,7))=="mailto:"||strtolower(substr($I1,11))=="javascript:"){
return $l1;
}else{
$I1 = $l3.$path."/".$I1;
}
return str_replace($I2,""$I1"",$l1);
}
?>

下面的链接是学习PHP正则表达式的地方。在这里留个链接,防止丢失。。。

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读