首页 > 解决方案 > php strpos()无法在字符串中找到括号

问题描述

当我使用 strpos() 时,如果该括号是字符串中的第一个字符,则无法找到“[”。我该如何克服这个问题,为什么会这样?

$name = "[johnny";
    if(strpos($name, "[") != false){
          echo "Bracket found!";}else{
            echo "Not found";
          }

在上面的代码中,当它不应该出现时,我得到“未找到”。

$name = "jo[hnny";
    if(strpos($name, "[") != false){
          echo "Bracket found!";}else{
            echo "Not found";
          }

但这种情况下正确返回“发现括号!”

标签: phpdebugging

解决方案


您必须使用!== false(双等号)

strpos 手册页

此函数可能返回布尔值 false,但也可能返回计算结果为 false 的非布尔值。请阅读有关布尔值的部分以获取更多信息。使用 === 运算符测试此函数的返回值。

以及页面上给出的示例:

$mystring = 'abc';
$findme   = 'a';
$pos = strpos($mystring, $findme);

// The !== operator can also be used.  Using != would not work as expected
// because the position of 'a' is 0. The statement (0 != false) evaluates
// to false.
if ($pos !== false) {
     echo "The string '$findme' was found in the string '$mystring'";
         echo " and exists at position $pos";
} else {
     echo "The string '$findme' was not found in the string '$mystring'";
}

推荐阅读