我写了这段代码:
$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
;如果找到,则返回标记在字符串中的(第一个)位置。您需要使用严格比较运算符 FALSE
检查布尔值 ===
来确定是否在字符串中找到标记:
if(strpos(strtolower($msg),strtolower($token)) !== false){
echo 'ok';
} else {
echo 'not ok';
}
这是因为 PHP 的松散类型系统。如果您使用
>=0
,并且未找到令牌,PHP 会在 FALSE
操作之前将 strpos
的 0
返回值转换为 >=
。并且 0 >=0
的计算结果为 TRUE
。
strpos()
返回 false。通过检查结果是否大于或等于零, false 被转换为整数,该整数变为零。所以零等于零,使你的 if 语句成立。
要解决此问题,只需查看
strpos()
是否返回 false:
if(strpos(strtolower($msg),strtolower($token)) !== false)
小心 strpos:
如果提供的变量中存在相应的字符串,则strpos 返回
position (number)
;如果根本不存在,则返回 boolean FALSE
。因此,如果您说 if(strpos(...)>=0)
,它总是会评估为 true,因为即使是 boolean FALSE evaluates to 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';
}
这是因为 php 自动转换。您还需要通过三重比较来检查类型。
这样做:
$token="Birth";
$msg="I am awesome and I know it";
if(strpos(strtolower($msg),strtolower($token)) !== false)
echo 'ok';