0

I've input field where visitor will have to enter URL and some may enter just www.some_site.com or http://www.some_site.com or https://www.some_site.com or even some_site.com.

i want no matter they entered is to make the output like http://www.some_site.com

will i use str_replace but how.

~ any help or idea else.

Reham Fahmy
  • 4,937
  • 15
  • 50
  • 71
  • 1
    You should use Regex instead: http://www.php.net/manual/en/function.preg-replace.php – Matthew Mar 22 '12 at 13:38
  • Related: http://stackoverflow.com/questions/5388061/php-format-a-website-url-with-http-if-not-present-more-of-a-string-thing – check123 Mar 22 '12 at 13:40

4 Answers4

2

Check out PHP's parse_url function.

if ($result['scheme'] == '' || $result['scheme'] == 'https') {
    $result['scheme'] = 'http';
}

Then put it back together using http_build_url

Captain Insaneo
  • 470
  • 2
  • 7
1

you can use following code

//$url = "https://www.google.com";
$url = "http://www.google.com";
//$url = "google.com";

echo convertUrl( $url); 

function convertUrl ( $url ) { 
  $parts = parse_url($url);
  //print_r( $parts);
  $returl = ""; 
  if ( empty($parts['scheme']) ) { 
    $returl = "http://" . $parts['path'];
  } else if ( $parts['scheme'] == 'https') {
    $returl = "http://" . $parts['host'];
  } else {
    $returl = $url;
  }

  return $returl;
}
Vijay Sharma
  • 373
  • 1
  • 10
0
$myURL = 'www.some_site.com/something_else/else/else.php'; //the normal URL
$myURL = explode('.some_site.com', $myURL); //break down the url by '.some_site.com'
$myURL = 'http://www.some_site.com/' . $myURL[1]; //add 'http://www.some_site.com/' and then add 'something_else/else/else.php'
echo $myURL;// OUTPUT: http://www.some_site.com//something_else/else/else.php
user3221512
  • 206
  • 3
  • 5
0
public function unifyUrl($sUrl){
 $exp = explode('://', $sUrl);
        if(count($exp) > 1)//means we have http or https
            $url = $exp[1];
        else
            $url = $exp[0];

        if(!preg_match('/^www\./', $url))//we are lack of www. in the beginning
            $url = 'www.'.$url;

        return 'http://'.$url;
    }
Michael
  • 1,067
  • 8
  • 13