tags:

views:

84

answers:

4

I'm trying to check if a string starts with http. How can I do this check?

$string1 = 'google.com';
$string2 = 'http://www.google.com';
+5  A: 

Use strpos():

if (0 === strpos($string2, 'http')) {
   // It starts with 'http'
}

Remember the three equals signs (===). It will not work properly if you only use two. This is because strpos() will return false if the needle cannot be found in the haystack.

awgy
It’s not necessary to search the whole string (`strpos` stops if the needle is found or the end is reached) if you just need to look at a specific position.
Gumbo
But in the worst case that there is no "http" in the string, it would require a full string search.
Kendall Hopkins
Which is trivial for short strings, but I'll upvote your substr() suggestion.
awgy
+3  A: 
substr( $string_n, 0, 4 ) === "http"

If you're trying to make sure it's not another protocol. I'd use http:// instead, since https would also match, and other things such as http-protocol.com.

substr( $string_n, 0, 7 ) === "http://"
Kendall Hopkins
A: 

Also work:

if (eregi("^http:", $url)) {
 echo "OK";
}
viriathus
A: 

there is also the strncmp() function and strncasecmp() function, perfect for this situation.

Sid