5

for my purposes I did this:

<?php
$mystring = 'Gazole,';
$findme   = 'Sans Plomb 95';
$pos = strpos($mystring, $findme);

if ($pos >= 0) {
    echo "The string '$findme' was found in the string '$mystring'";
    echo " and exists at position $pos";
} else {
    echo "The string '$findme' was not found in the string '$mystring'";
}
?>

However, it always executes this branch:

echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";

although the string I 'm searching for doesn't exist.

Please help, thx in advance :))

7 Answers 7

14

The correct way to do it is:

if ($pos !== false) {
    echo "The string '$findme' was found in the string '$mystring'";
    echo " and exists at position $pos";
} else {
    echo "The string '$findme' was not found in the string '$mystring'";
}

See the giant red warning in the documentation.

Sign up to request clarification or add additional context in comments.

Comments

3

strpos returns a boolean false in case the string was not found. Your test should be $pos !== false rather than $pos >= 0.

Note that the standard comparison operators do not consider the type of the operands, so that false is coerced to 0. The === and !== operators yield true only if the types and the values of the operands match.

Comments

1

See the warning on the manual page

You need also to check if $pos !== false

Comments

1

strpos() returns FALSE if the string was not found. When you check for $pos >= 0, you're accpeting that FALSE value.

Try this:

<?php
$mystring = 'Gazole,';
$findme   = 'Sans Plomb 95';
$pos = strpos($mystring, $findme);


if ($pos !== false) {
    echo "The string '$findme' was found in the string '$mystring'";
    echo " and exists at position $pos";
} else {
       echo "The string '$findme' was not found in the string '$mystring'";

}
?>

Comments

1

hi malek strpos method in php will return a boolean of value false when the string is not found and if found it will return the position in int.

refer this Link to study about strpos

Comments

0
if (strpos($mystring, $findme) !== false) {
    echo 'true';
}

Comments

0

Completely different way to do it without worrying about indexes:

if (str_replace($strToSearchFor, '', $strToSearchIn) <> $strToSearchIn) {
    //strToSearchFor is found inside strToSearchIn

What you are doing is replacing out any occurrence of the substring and checking if the result is the same as the original string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.