Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 将HTTP添加到url_Php_String_Url - Fatal编程技术网

Php 将HTTP添加到url

Php 将HTTP添加到url,php,string,url,Php,String,Url,我有一个函数,用于将http://添加到url,而url没有http://,如下所示 function addhttp($url) { if (!preg_match("~^(?:f|ht)tps?://~i", $url)) { $url = "http://" . $url; } return $url; } 我的问题是 如果我传递带有&的url,则将跳过&后面的字符串, 例如: 返回 我丢失了&pid=3308&treeid=1000这部分,如何修复此错误???我无

我有一个函数,用于将
http://
添加到url,而url没有
http://
,如下所示

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

return $url;
}
我的问题是

如果我传递带有
&
的url,则将跳过
&
后面的字符串, 例如:
返回


我丢失了
&pid=3308&treeid=1000
这部分,如何修复此错误???

我无法使用PHP5.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); 

I返回正确,但是如何以及在哪里传递url?这实际上是一个codeigniter函数,类似于$url=$This->addhttp($\u GET['u']);嗯,好吧,但是当我运行你的代码时,我真的没有丢失任何东西。我意识到$_GET['u']只返回。这就是问题所在,因为
&
之后是另一对。也许你应该在
之后得到查询另一个内置函数是
parse\u url('google.be',PHP\u url\u SCHEME)!==空
是的,很好的呼叫@DarkBee。但是,由于URL的scheme部分是否缺失,post PHP5.4.7函数的行为似乎发生了变化。查看手册页面上的第二个示例: