我编写了这段代码:
$token="Birth";
$msg="I am awesome and I know it";
if(strpos(strtolower($msg),strtolower($token)) >=0){
echo 'ok';
}
它会打印ok
正如我们所看到的,消息中没有像Birth
这样的单词,但它仍然返回true
。我猜应该返回false
,因为php手册上说了。
在这方面需要任何帮助,
strpos()
函数会在字符串中查找指定的字符或子字符串,如果找到则返回它在字符串中第一次出现的位置,未找到则返回FALSE
。你需要使用严格比较操作符===
来判断strpos()
是否返回了FALSE
,以确定在字符串中是否找到了指定的字符或子字符串:
if(strpos(strtolower($msg),strtolower($token)) !== false){
echo 'ok';
} else {
echo 'not ok';
}
这是由于PHP的松散类型系统。如果您使用“>=0”,并且未找到令牌,则PHP会将strpos的“假”返回值转换为“0”,然后进行“> =”操作。而“0> = 0”评估为“真”。strpos()
函数在未找到指定字符串时返回false。通过检查结果是否大于或等于零,将false转换为整数,其值为零。因此,零等于零,使得if语句为真。
要修复这个问题,只需检查strpos()
是否返回false:
if(strpos(strtolower($msg),strtolower($token)) !== false)
注意使用strpos函数:
如果提供的变量中存在对应的字符串,strpos函数会返回该字符串的位置(数字),否则返回布尔值FALSE。因此,如果你写if(strpos(...)>=0)
,它总是会被解析为true,因为即使boolean FALSE
也会被解析为0。实现这个功能的最佳方式是使用全等比较(hard compare)
。只需写
if(strpos(strtolower($msg),strtolower($token)) !== FALSE){
// The above line will tell PHP that treat the condition as passed
// only when strpos does not return The boolean FALSE.
echo 'ok';
}
$token="Birth";
$msg="I am awesome and I know it";
if(strpos(strtolower($msg),strtolower($token)) !== false)
echo 'ok';