例如,我输入以下网址:
http://www.example.com/
我希望它能归还我:
http://www.example.com
如何格式化这样的网址?是否有内置的PHP函数来执行此操作?
答案 0 :(得分:3)
这应该这样做:
$url = 'http://parkroo.com/';
if ( substr ( $url, 0, 11 ) !== 'http://www.' )
$url = str_replace ( 'http://', 'http://www.', $url );
$url = rtrim ( $url, '/' );
好的,这个应该更好用:
$urlInfo = parse_url ( $url );
$newUrl = $urlInfo['scheme'] . '://';
if ( substr ( $urlInfo['host'], 0, 4 ) !== 'www.' )
$newUrl .= 'www.' . $urlInfo['host'];
else
$newUrl .= $urlInfo['host'];
if ( isset ( $urlInfo['path'] ) && isset ( $urlInfo['query'] ) )
$newUrl .= $urlInfo['path'] . '?' . $urlInfo['query'];
else
{
if ( isset ( $urlInfo['path'] ) && $urlInfo['path'] !== '/' )
$newUrl .= $urlInfo['path'];
if ( isset ( $urlInfo['query'] ) )
$newUrl .= '?' . $urlInfo['query'];
}
echo $newUrl;
答案 1 :(得分:0)
您可以使用parse_url获取部分URL,然后构建URL。 或者更容易,修剪('http://example.com/','/');
答案 2 :(得分:0)
直播DEMO
<?php
function changeURL($url){
if(empty($url)){
return false;
}
else{
$u = parse_url($url);
/*
possible keys are:
scheme
host
user
pass
path
query
fragment
*/
foreach($u as $k => $v){
$$k = $v;
}
//start rebuilding the URL
if(!empty($scheme)){
$newurl = $scheme.'://';
}
if(!empty($user)){
$newurl.= $user;
}
if(!empty($pass)){
$newurl.= ':'.$pass.'@';
}
if(!empty($host)){
if(substr($host, 0, 4) != 'www.'){
$host = 'www.'. $host;
}
$newurl.= $host;
}
if(empty($path) && empty($query) && empty($fragment)){
$newurl.= '/';
}else{
if(!empty($path)){
$newurl.= $path;
}
if(!empty($query)){
$newurl.= '?'.$query;
}
if(!empty($fragment)){
$newurl.= '#'.$fragment;
}
}
return $newurl;
}
}
echo changeURL('http://yahoo.com')."<br>";
echo changeURL('http://username:password@yahoo.com/test/?p=2')."<br>";
echo changeURL('ftp://username:password@yahoo.com/test/?p=2')."<br>";
/*
http://www.yahoo.com/
http://username:password@www.yahoo.com/test/?p=2
ftp://username:password@www.yahoo.com/test/?p=2
*/
?>