
Question:
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?
Solution:1
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? }
Solution:2
preg_match('!^https?://!', $string)
Solution:3
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.
Solution:4
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.
Solution:5
$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://'; }
Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
EmoticonEmoticon