Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

substr - php problem: strpos function not working

why is the following php code not working:

$string = "123";
$search = "123";

if(strpos($string,$search))
{
    echo "found";
}else{
    echo "not found";
}

as $search is in $string - shouldn't it be triggered as found?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is mentioned in the Manual: strpos()

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.

In your case the string is found at the index 0 and in php 0 == false

The solution is to just use the strict comparator

echo strpos($string,$search) === false
     ? "not found"
     : "found";

Another one

echo is_int(strpos($string,$search))
     ? "found"
     : "not found";

Or something ... lets say interesting :D Just for illustration. I don't recommend this one.

echo strpos('_' . $string,$search) // we just shift the string 1 to the right
     ? "found"
     : "not found";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...