Zerium
Zerium

Reputation: 17333

How to format a URL in php?

For example, I enter this URL:

http://www.example.com/

And I want it to return me:

http://www.example.com

How can I format the URL like so? Is there a built-in PHP function for doing this?

Upvotes: 0

Views: 2194

Answers (3)

user1646111
user1646111

Reputation:

Live 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:[email protected]/test/?p=2')."<br>";
echo changeURL('ftp://username:[email protected]/test/?p=2')."<br>";
/*
http://www.yahoo.com/
http://username:[email protected]/test/?p=2
ftp://username:[email protected]/test/?p=2
*/
?>

Upvotes: 0

Jan Hančič
Jan Hančič

Reputation: 53931

This should do it:

$url = 'http://parkroo.com/';
if ( substr ( $url, 0, 11 ) !== 'http://www.' )
    $url = str_replace ( 'http://', 'http://www.', $url );

$url = rtrim ( $url, '/' );

Ok this one should work better:

$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;

Upvotes: 3

AKS
AKS

Reputation: 4658

You can parse_url to get parts of the URL and then build the URL. Or even easier, trim('http://example.com/', '/');

Upvotes: 0

Related Questions