预览模式: 普通 | 列表

Php不使用正则实现相对链接转绝对链接

调用方法:echo absolutepath(网页源码,网址);

PHP代码
  1. <?php  
  2. function absolutepath($html,$url){  
  3. //$url=current_url();  
  4. $url=strtolower($url);  
  5. $url=str_replace('http://','',$url);  
  6. $str=explode('/',$url);  
  7. $count=count($str);  
  8. $domain=$str[0];  
  9. for($i=1;$i<$count;$i++){  
  10.     $k=$count-$i;  
  11.     $path='';  
  12.     $absolutepath='';  
  13.     for($j=1;$j<$i;$j++){  
  14.         $absolutepath=$absolutepath.$str[$j].'/';  
  15.     }  
  16.     for($j=1;$j<$k;$j++){  
  17.         $path=$path.'../';  
  18.     }  
  19.     $html=str_replace('href="'.$path,'href="http://'.$domain.'/'.$absolutepath,$html);  
  20.     $html=str_replace('src="'.$path,'src="http://'.$domain.'/'.$absolutepath,$html);  
  21. }  
  22. $str=explode('href="',$html);  
  23. $count=count($str);  
  24. for($i=1;$i<$count;$i++){  
  25.     $str2=explode('"',$str[$i]);  
  26.     $url=$str2[0];  
  27.     if(strpos($url,'http://')>=0){  
  28.         $html=str_replace('href="'.$url,'href="'.$url,$html);  
  29.     }  
  30.     else{  
  31.         if(substr($url,0,1)=='/'){  
  32.             $url='http://'.$domain.$url;  
  33.         }  
  34.         else{  
  35.             $url='http://'.$domain.'/'.$url;  
  36.         }  
  37.         $html=str_replace('href="'.$url,'href="'.$url,$html);  
  38.     }  
  39. }  
  40. $str=explode('src="',$html);  
  41. $count=count($str);  
  42. for($i=1;$i<$count;$i++){  
  43.     $str2=explode('"',$str[$i]);  
  44.     $url=$str2[0];  
  45.     if(strpos($url,'http://')>=0){  
  46.         $html=str_replace('src="'.$url,'src="'.$url,$html);  
  47.     }  
  48.     else{  
  49.         if(substr($url,0,1)=='/'){  
  50.             $url='http://'.$domain.$url;  
  51.         }  
  52.         else{  
  53.             $url='http://'.$domain.'/'.$url;  
  54.         }  
  55.         $html=str_replace('src="'.$url,'src="'.$url,$html);  
  56.     }  
  57. }  
  58. return $html;  
  59. }  
  60. ?>  

原创代码,转载请注明出处www.jlist.cn

查看更多...

Tags: php

分类:技术文章 | 固定链接 | 评论: 1 | 引用: 0 | 查看次数: 3081

 广告位

↑返回顶部↑