I have a variable, lets say . . . $webaddress. I want to check and see if it starts with "http://"
If it doesn't, I'll stick it in there. I can handle that part, but how can I check for http:// at the beginning of the variable?
Thanks a million!
Check variable for HTTP at the beginning?
Moderator: General Moderators
- John Cartwright
- Site Admin
- Posts: 11470
- Joined: Tue Dec 23, 2003 2:10 am
- Location: Toronto
- Contact:
or like this:
Code: Select all
<?
$webaddress = "http://www.site.com";
if( substr($webaddress,0 ,7) == 'http://'){
echo "does start with http://";
} else {
echo "does not start with http://<br>";
}
?>- Chris Corbyn
- Breakbeat Nuttzer
- Posts: 13098
- Joined: Wed Mar 24, 2004 7:57 am
- Location: Melbourne, Australia
Well actually... let's say someone posts a link to an FTP site... would you want to replace it with http://ftp://foo.bar ? 
This checks simply for a protocol string at the beginning. (Untested)
EDIT | ftp may have been a bad example depending upon where this is used, https would be more sensible.
This checks simply for a protocol string at the beginning. (Untested)
Code: Select all
//Adds the http:// part to a given URL if not found
// If the optional second parameter is specified that
// protocol is used instead.
function addProtocol($url, $prot='http')
{
if (!preg_match('@^\w+://@', $url)) //Check for for the protocol
{
$url = $prot.'://'.$url; //Set one if not found
}
return $url;
}