tags:

views:

53

answers:

5

i have a string in $str variable.

how can i verify is it starts with some word?


example

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

when i wrote the following script

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

BUT it returns yes even when i wrote

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

i think it strpos returns zero if it can't find substring too(or empty value).

so, what can i do, if i want to verify the word, which in the start of string?(maybe i must use === in this case?)

Thanks

+1  A: 

You should check with the identity operator (===), see the documentation.

Dennis Haarbrink
hmmm, but how? i must verify if it `===` to what?
Syom
@Syom: Your test becomes: `if(strpos($str, "http://") === 0) echo "yes"; //returns yes`
Dennis Haarbrink
First of all, maybe you'd better use stripos() for these use cases since the url is partly case-insensitive. Furthermore, if you would want to check for https:// as well in one expression, use if ( preg_match("#https?://#i",$str) ) echo "yes";
mvds
+2  A: 

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.

cletus
Integer `0` obviously, not string `'0'`
JoostK
@JoostK: actually `'0' == 0` evaluates to `true`.
cletus
C'mon, that's just what this whole post is about!
JoostK
@JoostK sorry, I didn't see your point originally. Didn't notice my own typo. Thanks.
cletus
A: 
if(substr($str, 0, 7)=="http://") {
    echo("Statrs with http://");
}
ILMV
A: 

There's a big red warning in the documentation about this:

This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

strpos may return 0 or false. 0 is equal to false (0 == false). It is not identical to false however, which you can test with 0 === false. So the correct test is if (strpos(...) === 0).

Be sure to read up on the difference, it's important: http://php.net/manual/en/language.operators.comparison.php

deceze
+2  A: 

check with

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

as == will turn positive for both false & 0 check the documentation

Raja
why i can't write `'0'` insted of `0`?
Syom
Because `strpos` returns an integer if the string has been found. `===` matches only if the types matches as well, so `0 === '0'` won't match, since they differ in type (string vs. integer)
JoostK