大海捞针功能无法正常工作(偏移问题)


Needle in haystack function not working correctly (offset issue)

在这里我得到了这个函数:

public function strposa($haystack, $needles=array(), $offset) {
        $chr = array();
        foreach($needles as $needle) {
                $res = strpos($haystack, $needle, $offset);
                if ($res !== false) $chr[$needle] = $res;
        }
        if(empty($chr)) return false;
        return min($chr);
}

而这个:

   function usernameCurseWords($name) {
      $string = $name;
      $array  = array('bad', 'words', 'are', 'here');
      if (parent::strposa($string, $array, 0)) {
         return true;
      }
   }

我这样称呼它:

if ($this->usernameCurseWords($username)) { throw new Exception($error['userCurseWords']); }

如果大海捞针是"1bad",那么函数将返回true("bad"是一根针)。

但是,如果干草堆是"badblablbla",则该函数返回 false。

知道为什么这不能正常工作吗?

你知道strpos will 返回指针相对于干草堆字符串开头的位置(与偏移量无关)。另请注意,字符串位置从 0 开始,而不是 1。

因此,如果您的字符串位于 0 位置,则它将返回零。

但是在您的用户名CurseWords()中,它处于如果条件如此。

如果发现位置为零,则它将被视为假;明白我的意思了。

echo strpos('badall', 'bad',0);

将返回 0。在 0 位置找到 B/C 位置。

echo strpos('1badall', 'bad',0);
将返回在 1 个

位置找到的 1 个 b/c 位置。

if (parent::strposa($string, $array, 0)) {
     return true;
  }

但此行仅在返回为 1 时才接受。因此,请根据此更改代码。

if (parent::strposa($string, $array, 0) !== false) {
     return true;
  }

尝试类型匹配。

!== FALSE ... and 0 is not the same, FALSE is boolean, 0 (zero) not

所以只需使用

!=

这一行:if(empty($chr)) 返回假;

空 (0) = 真因此,当偏移量为零时,您将得到 true