2015-04-27 78 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