2015-04-27 79 views
0

我有一個用於將http://添加到URL,它不具有http://類似如下添加HTTP到URL

function addhttp($url) { 
if (!preg_match("~^(?:f|ht)tps?://~i", $url)) { 
     $url = "http://" . $url; 
    } 

return $url; 
} 

我的問題是一個功能,

如果我通過網址與&,在&後的字符串將跳過, 如:
https://www.example.com/Welcome/Default.aspx?scenarioID=360&pid=3308&treeid=1000 返回

https://www.example.com/Welcome/Default.aspx?scenarioID=360

我輸了&pid=3308&treeid=1000這部分,如何解決這個錯誤?

+0

我返回正確的,但如何和你在哪裏傳遞的網址是什麼? –

+0

這實際上是一個codeigniter函數,它會像$ url = $ this-> addhttp($ _ GET ['u']); – Shin

+0

嗯好吧,但我真的不會失去任何東西,當我運行你的代碼。 http://sandbox.onlinephpfunctions.com/code/67eb0e9fe39041db0ebb51ea975daa7fa424f818 –

回答

2

我無法重現使用PHP 5.5的錯誤。但是,我個人並不喜歡在構建執行此工作的函數時使用正則表達式。以下應該只是罰款爲正則表達式~^(?:f|ht)tps?://~i更換:

<?php 
function addhttp($url, $https=false) { 
    $protocols = ['https://', 'http://', 'ftps://', 'ftp://']; 
    $heystack = strtolower(substr($url, 0, 8)); 
    foreach ($protocols as $protocol) { 
     if (strpos($heystack, $protocol) === 0) { 
      return $url; 
     } 
    } 
    return ($https ? 'https://' : 'http://') . $url; 
} 

$url = 'www.example.com/Welcome/Default.aspx?scenarioID=360&pid=3308&treeid=1000'; 
// for http:// 
echo addhttp($url); 
// for https:// 
echo addhttp($url, true); 

我在這裏添加一個可選的參數,如果你不喜歡它,只是把它拿出來,並取出三元表達(<expression> ? true : false)

如果你需要得到URL的價值看this question

+1

另一個內建函數是'parse_url('google.be',PHP_URL_SCHEME)!== null' – DarkBee

+0

是的,很好致電@DarkBee。但是它看起來像PHP 5.4.7中特定於URL的方案部分不存在或不存在的功能發生了變化。請查看手冊頁面上的第二個示例:http://php.net/manual/en/function.parse-url.php – robbmj