脚本宝典收集整理的这篇文章主要介绍了php – 将相对URL转换为绝对URL,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
function absolute_url($url,$parent_url){ $parent_url=parse_url($parent_url); if(strcmp(substr($url,7),'http://')==0){ return $url; } elseif(strcmp(substr($url,1),'/')==0){ return $parent_url['scheme']."://".$parent_url['host'].$url; } else{ $path=$parent_url['path']; $path=substr($path,strrpos($path,'/')); return $parent_url['scheme']."://".$parent_url['host']."$path/".$url; } } $parent_url='http://example.COM/path/to/file/name.PHP?abc=abc'; echo absolute_url('name2.PHP',$parent_url)."\n"; // output http://example.com/path/to/file/name2.PHP echo absolute_url('/name2.PHP',$parent_url)."\n"; // output http://example.com/name2.PHP echo absolute_url('http://name2.PHP',$parent_url)."\n"; // output http://name2.PHP
代码工作正常,但可能有更多的情况,如../../path/to/file.PHP,这将无法正常工作.
/home.PHP?example类型,
same-dir nextpage.PHP类型,
../…../…/parentdir类型,
完整的http://example.net网址,
和简写//example.net网址
//current base URL (you can dynamically retrieve From $_SERVER) $pgurl = 'http://example.com/scripts/PHP/absurl.PHP'; function absurl($url) { global $pgurl; if(strpos($url,'://')) return $url; //already absolute if(substr($url,2)=='//') return 'http:'.$url; //shorthand scheme if($url[0]=='/') return parse_url($pgurl,PHP_URL_SCHEME).'://'.parse_url($pgurl,PHP_URL_HOST).$url; //just add domain if(strpos($pgurl,'/',9)===false) $pgurl .= '/'; //add slash to domain if needed return substr($pgurl,strrpos($pgurl,'/')+1).$url; //for relative links,gets current directory and apPEnds new filename } function nodots($path) { //Resolve dot dot slashes,no regex! $arr1 = explode('/',$path); $arr2 = array(); foreach($arr1 as $seg) { swITch($seg) { case '.': break; case '..': array_pop($arr2); break; case '...': array_pop($arr2); array_pop($arr2); break; case '....': array_pop($arr2); array_pop($arr2); array_pop($arr2); break; case '.....': array_pop($arr2); array_pop($arr2); array_pop($arr2); array_pop($arr2); break; default: $arr2[] = $seg; } } return implode('/',$arr2); }
用法示例:
echo nodots(absurl('../index.htML'));
点函数有点冗余,但是可读,快速,不使用正则表达式,并且将解析99%的典型网址(如果你想100%确定,只需扩展开关块以支持6点,虽然我从来没有在URL中看到过那么多点.
希望这可以帮助,
以上是脚本宝典为你收集整理的php – 将相对URL转换为绝对URL全部内容,希望文章能够帮你解决php – 将相对URL转换为绝对URL所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。