Keith
Keith

Reputation: 11

find string match

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?

Upvotes: 1

Views: 459

Answers (5)

Shah
Shah

Reputation: 505

$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://';    
}

Upvotes: 0

Gordon
Gordon

Reputation: 316959

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.

Upvotes: 1

Gordon
Gordon

Reputation: 316959

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.

Upvotes: 3

Wrikken
Wrikken

Reputation: 70460

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?
}

Upvotes: 6

SilentGhost
SilentGhost

Reputation: 319531

preg_match('!^https?://!', $string)

docs

Upvotes: 4

Related Questions