【问题标题】:PHP strpos() return empty valuePHP strpos() 返回空值
【发布时间】:2019-03-05 15:40:21
【问题描述】:

我遇到了一个奇怪的 PHP 函数 strpos()。 我有一个函数可以检查是否在 txt 文件中找到传递的字符串。 我可以逐行显示文件的内容,但 strpos() 不返回值(实际上什么都没有)。 var_dump() 的返回空。

有人能看出错误吗,因为我迷路了。 提前谢谢你。

我的功能:

function checkIfExist($string)
{
    $path = "\\\\server\\temp\\test.txt";
    $file = file($path);
    foreach( $file as $line )
    {   
       echo $line; //display the string in this line
       $found = strpos($file,$string);
       echo $found; //display nothing, not even a boolean/int 
}
return $found;
}

【问题讨论】:

  • 看起来您是在文件的整个内容中而不是在每一行中查找字符串。根据$string 的内容和您可能无法匹配的文件。

标签: php string compare strpos


【解决方案1】:

尝试将$found = strpos($file,$string);改为$found = strpos($line,$string);

【讨论】:

    【解决方案2】:

    不会显示回显错误布尔值。尝试将其更改为var_dump,您将看到它是一个设置为falseboolean

    【讨论】:

      【解决方案3】:

      对不起,我写代码时出错了,这是好的:

      function checkIfExist($string)
      {
          $path = "\\\\server\\temp\\test.txt";
          $file = file($path);
          foreach( $file as $line )
          {   
             echo $line; //display the string in this line
             $found = strpos($line,$string);
             echo $found; //display nothing, not even a boolean/int
             var_dump($found); //display boolena(false) for all the test even if the 
                               string is well present once.
      
      
      }
          return $found;
      }
      

      【讨论】:

        【解决方案4】:

        此代码给出相同的结果

        foreach( $file as $line )
        {   
            echo $line; //display "www.google.be"
            echo $string; //also display "www.google.be"
            //but when I then if the line contain the string, the function doesn't find 
              it!!!
            $pos = stripos($line,$hostname);
            var_dump($pos); // FALSE for all the test
        }
        

        我在其他代码中做过这个,我从来没有遇到过这个问题。

        【讨论】:

          【解决方案5】:

          设置调试,让您看到 strpos 的值。如果无法安排调试比 vardump $line 和 $string。您可能会得到意想不到的值。还要尝试避免类型转换问题。也许这会更好。

          if (strpos($line,$string) != false){...}else{...}
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-01-24
            • 2016-04-10
            • 1970-01-01
            • 2015-01-25
            • 2013-07-07
            • 1970-01-01
            相关资源
            最近更新 更多