Checking if string contains "HTTP://"
I am wondering why this code is not working:
// check to see if string contains "HTTP://" in front
if(strpos($URL, "http://"开发者_JAVA技巧)) $URL = $URL;
else $URL = "http://$URL";
If it does find that the string doesn't contain "HTTP://" the final string is "HTTP://HTTP://foo.foo" if it contiains "http://" in front.
Because it's returning 0 for that string, which evaluates to false. Strings are zero-indexed and as such if http://
is found at the beginning of the string, the position is 0, not 1.
You need to compare it for strict inequality to boolean false using !==
:
if(strpos($URL, "http://") !== false)
@BoltClock's method will work.
Alternatively, if your string is a URL you can use parse_url(), which will return the URL components in an associative array, like so:
print_r(parse_url("http://www.google.com.au/"));
Array
(
[scheme] => http
[host] => www.google.com.au
[path] => /
)
The scheme
is what you're after. You can use parse_url() in conjunction with in_array
to determine if http
exists within the URL string.
$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
{
}
Edit:
You can use $url["scheme"]=="http"
as @mario suggested instead of in_array()
, this would be a better way of doing it :D
if(preg_match("@^http://@i",$String))
$String = preg_replace("@(http://)+@i",'http://',$String);
else
$String = 'http://'.$String;
You need to remember about https://
.
Try this:
private function http_check($url) {
$return = $url;
if ((!(substr($url, 0, 7) == 'http://')) && (!(substr($url, 0, 8) == 'https://'))) {
$return = 'http://' . $url;
}
return $return;
}
you have checking if string contains “HTTP://” OR Not
Below code is perfectly working.
<?php
$URL = 'http://google.com';
$weblink = $URL;
if(strpos($weblink, "http://") !== false){ }
else { $weblink = "http://".$weblink; }
?>
<a class="weblink" <?php if($weblink != 'http://'){ ?> href="<?php echo $weblink; ?>"<?php } ?> target="_blank">Buy Now</a>
Enjoy guys...
You can use substr_compare() [PHP Docs].
Be careful about what the function returns. If the strings match, it returns 0. For other return values you can check the PHP docs. There is also a parameter to check case-sensitive strings. If you specify it TRUE then it will check for upper-case letters.
So you can simply write as follows in your problem:
if((substr_compare($URL,"http://",0,7)) === 0) $URL = $URL;
else $URL = "http://$URL";
One line solution:
$sURL = 'http://'.str_ireplace('http://','',$sURL);
精彩评论