2012-03-22 69 views
0

URL過濾我已經輸入字段,遊客必須輸入URL和一些可以只輸入www.some_site.comhttp://www.some_site.comhttps://www.some_site.com 甚至some_site.com與str_replace函數

我想不管他們進入是使輸出像http://www.some_site.com

將我使用str_replace而是如何。

〜其他任何幫助或想法。

+1

您應該使用正則表達式來代替:http://www.php.net /manual/en/function.preg-replace.php – Matthew 2012-03-22 13:38:32

+0

相關:http://stackoverflow.com/questions/5388061/php-format-a-website-url-with-http-if-not-present-m礦石的-A-串的事情 – check123 2012-03-22 13:40:06

回答

1

你可以用下面的代碼

//$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; 
} 
2

查看PHP的parse_url函數。

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

然後把它重新走到一起使用http_build_url

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