3

I was having trouble with a longer func i wrote, so i broke it down and it seems to be with the strpos() function.

Even though the needle is clearly present in the haystack it returns false, for the life of me i cant work out why, oddly though if i change the needle to "sam" in becomes true.. any idea why ?

function verify_url($url) {
    if (strpos($url, "http://")) {
        return $url;
    } else {
        echo "error";
    }
}


$url = "http://sam.com";

echo verify_url($url);
4

2 回答 2

9

It is returning 0, not false. In the if test PHP evaluates integer value 0 as boolean value false.

Use strpos($url, "http://") !== false to check both value and data type. It is called strict comparison.

Manual: Comparison Operators and strpos().

于 2013-05-15T12:12:43.090 回答
2

Replace your if (strpos($url, "http://")) with below one.

if (strpos($url, "http://") !== false)

It's giving 0 (and not false) because it found http:// at 0th position

于 2013-05-15T12:13:39.733 回答