php strpos 总是返回false,我想得到一个正确的答案

php strpos always returning false,i want to get a right answer

我拿到一个项目,看到一段代码如下:

<?php
$orderby=$_REQUEST['orderby'];
if(strpos($orderby,'d')===true){
    echo "exists";
}else{
    echo "not ";
}?>

无论如何,我输入 'd' 或其他参数页面总是返回 'not'。 那么,如何输入正确的参数让页面返回'exists'?

您的测试并不是说它是 returning false,只是 strpos() 永远不会 return 是布尔值 true。相反,它将 return 一个包含找到的字符串位置的整数。通常支票是

if(strpos($orderby,'d') !== false){
    echo "exists";
}else{
    echo "not ";
}

如果 strpos 找到匹配项,它不会返回 true 但会返回偏移量 - 因此您的 strpos($orderby,'d')===true 永远不会被命中。

试试这个:

<?php
$orderby=$_REQUEST['orderby'];
if($o=strpos($orderby,'d')===false){
    echo "not ";
}else{
    echo "exists at offset $o";
}?>

strpos() 永远不会 return TRUE。如果找到该字符串,它就是 return 的位置。如果未找到字符串 returns FALSE。所以你应该比较 FALSE,而不是 TRUE.

if (strpos($orderby, 'd') === false) {
    echo "not exists";
} else {
    echo "exists";
}