verify, if the string starts with given substring
You should check with the identity operator (===), see the documentation.
Your test becomes:
if (strpos($str, 'http://') === 0) echo 'yes';
As @Samuel Gfeller pointed out: As of PHP8 you can use the str_starts_with() method. You can use it like this:
if (str_starts_with($str, 'http://')) echo 'yes';
You need to do:
if (strpos($str, "http://") === 0) echo "yes"
The ===
operator is a strict comparison that doesn't coerce types. If you use ==
then false
, an empty string, null
, 0
, an empty array and a few other things will be equivalent.
See Type Juggling.
PHP does have 2 functions to verify if a string starts with a given substring:
strncmp
(case sensitive);strncasecmp
(case insensitive);
So if you want to test only http (and not https), you can use:
if (strncasecmp($str,'http://',7) == 0) echo "we have a winner"