网络实验室

 找回密码
 注册账户
查看: 125373|回复: 0

PHP版,文章采集URL补全函数:formaturl

[复制链接]
无心的棋子 发表于 2007-6-26 15:22:03 | 显示全部楼层 |阅读模式
HS英文文章发布系统 准备增加采集 所以收藏此函数

写采集必用的函数,URL补全函数,也可叫做FormatUrl。

写此函数作用就是为了开发采集程序,采集文章的时候会经常遇到页面里的路径是 “相对路径” 或者 “绝对根路径” 不是“绝对全路径”就无法收集URL。

所以,就需要本功能函数进行对代码进行格式化,把所有的超链接都格式化一遍,这样就可以直接收集到正确的URL了。

路径知识普及
相对路径:“../” “./” 或者前面什么都不加
绝对根路径:/path/xxx.html
绝对全路径:http://www.xxx.com/path/xxx.html

使用实例:


  1. <?php
  2. $surl="http://www.7lian.com/";
  3. $gethtm = '<a href="/index.htm">首页</a><a href="Resolvent/index.htm">解决方案</a>';
  4. echo formaturl($gethtm,$surl);
  5. ?>
复制代码

输出:<a href="http://www.7lian.com/index.htm">首页</a><a href="http://www.7lian.com/Resolvent/index.htm">解决方案</a>




  1. <?php
  2. function formaturl($l1,$l2){
  3. if (preg_match_all("/(<img[^>]+src="([^"]+)"[^>]*>)|(<a[^>]+href="([^"]+)"[^>]*>)|(<img[^>]+src='([^']+)'[^>]*>)|(<a[^>]+href='([^']+)'[^>]*>)/i",$l1,$regs)){
  4.      foreach($regs[0] as $num => $url){
  5.       $l1 = str_replace($url,lIIIIl($url,$l2),$l1);
  6.      }
  7. }
  8. return $l1;
  9. }
  10. function lIIIIl($l1,$l2){
  11. if(preg_match("/(.*)(href|src)=(.+?)( |/>|>).*/i",$l1,$regs)){$I2 = $regs[3];}
  12. if(strlen($I2)>0){
  13.      $I1 = str_replace(chr(34),"",$I2);
  14.      $I1 = str_replace(chr(39),"",$I1);
  15. }else{return $l1;}
  16. $url_parsed = parse_url($l2);
  17. $scheme     = $url_parsed["scheme"];if($scheme!=""){$scheme = $scheme."://";}
  18. $host     = $url_parsed["host"];
  19. $l3      = $scheme.$host;
  20. if(strlen($l3)==0){return $l1;}
  21. $path     = dirname($url_parsed["path"]);if($path[0]==""){$path="";}
  22. $pos     = strpos($I1,"#");
  23. if($pos>0) $I1 = substr($I1,0,$pos);

  24. //判断类型
  25. if(preg_match("/^(http|https|ftp):(//|\\)(([w/\+-~`@:%])+.)+([w/\.=?+-~`@':!%#]|(&)|&)+/i",$I1)){return $l1; }//http开头的url类型要跳过
  26. elseif($I1[0]=="/"){$I1 = $l3.$I1;}//绝对路径
  27. elseif(substr($I1,0,3)=="../"){//相对路径
  28.      while(substr($I1,0,3)=="../"){
  29.       $I1 = substr($I1,strlen($I1)-(strlen($I1)-3),strlen($I1)-3);
  30.       if(strlen($path)>0){
  31.        $path = dirname($path);
  32.       }
  33.      }
  34.      $I1 = $l3.$path."/".$I1;
  35. }
  36. elseif(substr($I1,0,2)=="./"){
  37.      $I1 = $l3.$path.substr($I1,strlen($I1)-(strlen($I1)-1),strlen($I1)-1);
  38. }
  39. elseif(strtolower(substr($I1,0,7))=="mailto:"||strtolower(substr($I1,0,11))=="javascript:"){
  40.      return $l1;
  41. }else{
  42.      $I1 = $l3.$path."/".$I1;
  43. }
  44. return str_replace($I2,""$I1"",$l1);
  45. }
  46. ?>
复制代码
您需要登录后才可以回帖 登录 | 注册账户

本版积分规则

黑屋|存档|手机|网络实验室 本站服务器由美国合租以及IDCLayer国际数据提供!!!

GMT+8, 2024-4-29 06:08 , Processed in 0.694344 second(s), 10 queries , Gzip On, Redis On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表