I need to check a variable to see if the string starts with http:// or https://
if it exists do something else do another. How would I go about doing that?
I need to check a variable to see if the string starts with http:// or https://
if it exists do something else do another. How would I go about doing that?
The question is unclear. If you just want to know if the string starts with either http or https, you can use
$startsWithIt = (strpos($haystack, 'http') === 0);
If you want the check to include ://
you have to do:
if((strpos($haystack, 'http://') === 0) ||
(strpos($haystack, 'https://') === 0)) {
echo 'Strings starts with http:// or https://';
}
If you need to know which of the two it is, use Wrikken's answer.
You're probably looking for:
switch(parse_url($string, PHP_URL_SCHEME)){
case 'https':
//do something
case 'http':
//something else
default:
//anything else you'd like to support?
}
Here is another one:
function startsWithHttpOrHttps($haystack)
{
return substr_compare($haystack, 'http://', 0, 7) === 0
|| substr_compare($haystack, 'https://', 0, 8) === 0;
}
On my machine, this outperformed my double strpos
solution (even with added substr
to prevent going over the full length string) and Regex.