检查字符串是否包含“HTTP://”
我想知道为什么这个代码不起作用:
// 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://”。
我想知道为什么这个代码不起作用:
// 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://”。
因为它为该字符串返回 0,其计算结果为 false。字符串的索引为零,因此,如果在字符串的开头找到,则位置为 0,而不是 1。http://
您需要使用以下命令将其与布尔假的严格不等式进行比较:!==
if(strpos($URL, "http://") !== false)
@BoltClock的方法将起作用。
或者,如果您的字符串是 URL,则可以使用 parse_url(),它将返回关联数组中的 URL 组件,如下所示:
print_r(parse_url("http://www.google.com.au/"));
Array
(
[scheme] => http
[host] => www.google.com.au
[path] => /
)
这就是你所追求的。您可以将 parse_url() 结合使用来确定 URL 字符串中是否存在。scheme
in_array
http
$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
{
}
编辑:
您可以按照建议@mario而不是 ,这将是更好的方法,:D$url["scheme"]=="http"
in_array()