例如,我输入这个 URL:
http://www.example.com/
我希望它返回我:
http://www.example.com
我怎样才能像这样格式化 URL?是否有内置的 PHP 函数来执行此操作?
这应该这样做:
$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;
您可以通过 parse_url 获取部分 URL,然后构建 URL。或者更简单, trim(' http://example.com/ ', '/');
现场演示
<?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
*/
?>