Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

verify, if the string starts with given substring

Tags:

php

I have a string in $str variable.

How can I verify if it starts with some word?


Example:

$str = "http://somesite.com/somefolder/somefile.php";

When I wrote the following script returns yes

if(strpos($str, "http://") == '0') echo "yes";

BUT it returns yes even when I wrote

if(strpos($str, "other word here") == '0') echo "yes";

I think strpos returns zero if it can't find substring too (or a value that evaluates to zero).

So, what can I do if I want to verify if word is in the start of string? Maybe I must use === in this case?

like image 459
Simon Avatar asked Sep 04 '25 16:09

Simon


1 Answers

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.

like image 80
cletus Avatar answered Sep 07 '25 17:09

cletus