【问题标题】:PHP's strpos() not working and always getting into the if conditionPHP strpos() 不工作并且总是进入 if 条件
【发布时间】:2019-01-08 15:41:43
【问题描述】:

我正在尝试检查我的代码中的字符串中是否不存在特定字符,显然 php 不关心任何事情,并且总是进入 if

foreach($inserted as $letter)
{
    if(strpos($word, $letter) !== true) //if $letter not in $word
    {
        echo "$word , $letter, ";
        $lives--;
    }
}

在这种情况下,$word 是“abc”,$letter 是“b”,我尝试了很多随机的东西,比如从 true 到 false 之类的东西,但我无法理解,谁能帮忙请问我?

【问题讨论】:

  • 那是因为strpos()从不返回true
  • 你误会了。 strpos() 没有任何状态可以 返回true。这是该函数的无效返回值。您不妨写:if (strpos($word, $letter) !== 'FooBarHelloWorld')。该函数仅返回false(如果未找到该字符串)或整数(从0 及以上)以及大海捞针中针的位置。
  • @EgidioPignataro Magnus 的意思是 strpos 永远不会返回 true,所以因为您的 if 语句正在检查“不正确”(并且 strpos 永远不会返回 true),所以它将始终输入你的 if 块。
  • 所以我应该试试 if(strpos($word, $letter) === false) 代替?
  • 建议:如果您以后对 PHP 函数有任何疑问,请先检查 manual 并阅读返回值。

标签: php strpos


【解决方案1】:

更改验证方式应该可以解决它,如下所示:

     foreach($inserted as $letter)
        {
            //strpos returns false if the needle wasn't found
            if(strpos($word, $letter) === false) 
            {
                echo "$word , $letter, ";
                $lives--;
            }
        }

【讨论】:

  • 其他人似乎给出了相同的答案:Magnus Eriksson
  • 好吗?谢谢你让我知道,我猜? :-p
  • @lucid 只有 1 个其他较新的答案,而 cmets 不是答案。
【解决方案2】:
if(strpos($word, $letter) === false) //if $letter not in $word
{
    echo "$word , $letter, ";
    $lives--;
}

另外,请注意明确检查 false,如果匹配在字符串的第 0 个索引中,strpos 可以返回 0(错误值)...

例如

if (!strpos('word', 'w') {
    echo 'w is not in word';
}

将输出可能令人困惑的消息'w is not in word'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-27
    • 1970-01-01
    • 2013-01-13
    • 2019-10-13
    • 1970-01-01
    • 2019-04-16
    • 1970-01-01
    相关资源
    最近更新 更多