strpos在字符串中找不到一个单词


strpos not finding one word in a string

在下面的代码中,如果我将$what设置为"red",它不会找到它,而会找到绿色和蓝色。为什么以及如何让它也变成红色?

$where = 'red,green,blue';
$what = 'blue';
if (strpos($where, $what) == true) {
    echo 'found';
}

strpos返回找到的字符串的索引。在这种情况下,索引为0,您对== true的检查将失败。尝试:

strpos($where, $what) !== false

文档提供了更多信息。

如果字符串不存在,

strpos将返回false。否则,它将返回字符串的位置。

在这种情况下,"red"位于字符串的开头,这意味着它位于位置0;0的计算结果为false。

您需要对结果进行布尔比较:

if(strpos($word, 'red') === false)