Php不使用正则实现相对链接转绝对链接
作者:admin 日期:2012-06-08
调用方法:echo absolutepath(网页源码,网址);
PHP代码
- <?php
- function absolutepath($html,$url){
- //$url=current_url();
- $url=strtolower($url);
- $url=str_replace('http://','',$url);
- $str=explode('/',$url);
- $count=count($str);
- $domain=$str[0];
- for($i=1;$i<$count;$i++){
- $k=$count-$i;
- $path='';
- $absolutepath='';
- for($j=1;$j<$i;$j++){
- $absolutepath=$absolutepath.$str[$j].'/';
- }
- for($j=1;$j<$k;$j++){
- $path=$path.'../';
- }
- $html=str_replace('href="'.$path,'href="http://'.$domain.'/'.$absolutepath,$html);
- $html=str_replace('src="'.$path,'src="http://'.$domain.'/'.$absolutepath,$html);
- }
- $str=explode('href="',$html);
- $count=count($str);
- for($i=1;$i<$count;$i++){
- $str2=explode('"',$str[$i]);
- $url=$str2[0];
- if(strpos($url,'http://')>=0){
- $html=str_replace('href="'.$url,'href="'.$url,$html);
- }
- else{
- if(substr($url,0,1)=='/'){
- $url='http://'.$domain.$url;
- }
- else{
- $url='http://'.$domain.'/'.$url;
- }
- $html=str_replace('href="'.$url,'href="'.$url,$html);
- }
- }
- $str=explode('src="',$html);
- $count=count($str);
- for($i=1;$i<$count;$i++){
- $str2=explode('"',$str[$i]);
- $url=$str2[0];
- if(strpos($url,'http://')>=0){
- $html=str_replace('src="'.$url,'src="'.$url,$html);
- }
- else{
- if(substr($url,0,1)=='/'){
- $url='http://'.$domain.$url;
- }
- else{
- $url='http://'.$domain.'/'.$url;
- }
- $html=str_replace('src="'.$url,'src="'.$url,$html);
- }
- }
- return $html;
- }
- ?>
原创代码,转载请注明出处www.jlist.cn!
广告位