Question about strpos in PHP

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

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

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

it 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: [Empty] found

Now, if I changed the comparator and used "! = 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 am looking for a substring at the beginning of a line. For example, this will lead to the conclusion "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 do this? 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 whole string ...

+2
source share
2 answers

Testing with an operator !==. This will compare types and values, not just values:

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

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

, ... ! == false ! =... Aaaah, php.

+2

Source: https://habr.com/ru/post/1720533/


All Articles