Reputation: 2123
I have a input that you enter a URL, i basically want to write some php that says if the domain containts "http://" then leave it be, else if not then add it to the beginning. This is what I have so far...
$domain = $_POST["domain"];
if (strpos($domain, "http://")) {
return $domain;
} else {
$domain = "http://" . $domain;
}
This doesnt seem to work..
it doesnt add the http:// on if it doesnt contain http://.
Upvotes: 0
Views: 1207
Reputation: 619
I know this is a bit late to the party, but I prefer this approach:
if (!preg_match('#^http[s]{0,1}://#', $input)) {
$input = 'http://' . $input;
}
This will preserve a https:// address, and not have you ending up with http://https://www.mysite.com
. You could also further edit it to strip out https:// if you had a rule for not using https addresses.
I know the original question didn't ask for this, but I think it's important to consider in most situations, and will hopefully help someone else who comes looking.
Upvotes: 1
Reputation: 538
if (strpos($domain, "http://") !== false) {
//return substr($domain,7); Thanks Rocket.
return $domain;
} else {
return "http://" . $domain;
}
Upvotes: 1
Reputation: 28936
Use caution when using strpos(). It will return 0 when 'http://' is found at the beginning of the string, causing your if statement to fail unexpectedly. You will want to check the type of the return to be sure:
$domain = $_POST["domain"];
if (FALSE !== strpos($domain, "http://")) {
return $domain;
} else {
return "http://" . $domain;
}
Upvotes: 0
Reputation: 17703
you forgot to return $domain.
$domain = $_POST["domain"];
if (strpos($domain, "http://") !== false) {
return $domain;
} else {
return "http://" . $domain;
}
Upvotes: 6
Reputation: 18859
"http://" then leave it be, else if not then add it to the beginning.
How about adding adding it regardless? I find that to be easier:
<?php
$url = 'http://www.google.com';
echo 'http://' . preg_replace( '~^http://~', '', $url );
Upvotes: 4
Reputation: 14951
That is because strpos will return the location of the string, within the string. In your url, that is 0. Which equals to false. Make it a strict check - add === false.
Upvotes: 2
Reputation: 227310
Since the string starts with http://
, strpos
will return 0
, which will evaluate to false.
Change the if statement to:
if(strpos($domain, "http://") !== FALSE){
Upvotes: 5
Reputation:
read manual:
This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.
Upvotes: 2