我想知道为什么这段代码不起作用:
// check to see if string contains "HTTP://" in front
if(strpos($URL, "http://")) $URL = $URL;
else $URL = "http://$URL";
如果它确实发现该字符串不包含"HTTP://",则最终字符串为"HTTP:// HTTP://foo.foo",如果它在前面包含"http://".
Bol*_*ock 37
因为它为该字符串返回0,该字符串的计算结果为false.字符串是零索引的,因此如果http://在字符串的开头找到,则位置为0,而不是1.
您需要使用以下方法将严格不等式与布尔值false进行比较!==:
if(strpos($URL, "http://") !== false)
Rus*_*ias 11
@ BoltClock的方法将起作用.
或者,如果您的字符串是URL,则可以使用parse_url(),它将返回关联数组中的URL组件,如下所示:
print_r(parse_url("http://www.google.com.au/"));
Array
(
    [scheme] => http
    [host] => www.google.com.au
    [path] => /
)
这scheme就是你所追求的.您可以结合使用parse_url()in_array来确定httpURL字符串中是否存在.
$strUrl       = "http://www.google.com?query_string=10#fragment";
$arrParsedUrl = parse_url($strUrl);
if (!empty($arrParsedUrl['scheme']))
{
    // Contains http:// schema
    if ($arrParsedUrl['scheme'] === "http")
    {
    }
    // Contains https:// schema
    else if ($arrParsedUrl['scheme'] === "https")
    {
    }
}
// Don't contains http:// or https://
else
{
}
编辑:
您可以使用$url["scheme"]=="http"@mario建议代替in_array(),这将是一种更好的方法:D
if(preg_match("@^http://@i",$String))
    $String = preg_replace("@(http://)+@i",'http://',$String);
else
    $String = 'http://'.$String;
小智 5
您需要记住https://。尝试这个:
private function http_check($url) {
    $return = $url;
    if ((!(substr($url, 0, 7) == 'http://')) && (!(substr($url, 0, 8) == 'https://'))) {
        $return = 'http://' . $url;
    }
    return $return;
} 
| 归档时间: | 
 | 
| 查看次数: | 40825 次 | 
| 最近记录: |