tags:

views:

72

answers:

2

I'm just trying to figure that out...

$mystring = "/abc/def/hij";
$find = "/abc";

echo(strpos($mystring, $find) . "<br>");
if (strpos($mystring, $find) >= 0) {
    echo("found");
} else {
    echo("not found");
}

this will give : 0 found

$mystring = "/abc/def/hij";
$find = "/fffff";

echo(strpos($mystring, $find) . "<br>");
if (strpos($mystring, $find) >= 0) {
    echo("found");
} else {
    echo("not found");
}

output : [blank] found

Now if I change the comparator and use "!= False" instead of ">= 0"

$mystring = "/abc/def/hij";
$find = "/fffff";

echo(strpos($mystring, $find) . "<br>");
if (strpos($mystring, $find) **!= false**) {
    echo("found");
} else {
    echo("not found");
}

This works in almost all cases, except when I look for the substring at the beginning of the string. For example, this will output "not found" :

$mystring = "/abc/def/hij";
$find = "/abc";

echo(strpos($mystring, $find) . "<br>");
if (strpos($mystring, $find) != false) {
    echo("found");
} else {
    echo("not found");
}

So how can I make that work? I just want to know if a substring exists in a string, and it should give me "true" if the substring is the beginning or the entire string...

+1  A: 

I found what the problem was... I need to use !== false instead of != ... Aaaah, php.

mrmuggles
Consequently, there is a big warning under "Return Values" on the documentation page for strpos that describes this. http://us2.php.net/manual/en/function.strpos.php
Sean Bright
+2  A: 

Test using the !== operator. This will compare types and values, as opposed to just values:

$mystring = "/abc/def/hij";
$find = "/abc";

echo(strpos($mystring, $find) . "<br>");
if (strpos($mystring, $find) !== false) {
    echo("found");
} else {
    echo("not found");
}
John Rasch