php中的字符串比较不起作用


String Comparison in php is not working

我试图打开一个文件,并将每行与字符串进行比较,看看它们是否相同,但它不工作,这里是代码。

$toSearch="moizhusnain@hotmail.com";
$textData=array();
$fla=FALSE;
$file=fopen('text.txt','r') or die('Unable to open file.');
while(!feof($file))
{
  $textData[]=fgets($file);
}
fclose($file);
for($i=0;$i<count($textData);$i++)
{
  echo $textData[$i]."<br/>";
  if (strcmp($toSearch,$textData[$i])==0)
  {
      echo "Yes";
  }
}

试试这个

if (strcasecmp ($toSearch,$textData[$i])==0){ //case insensitive comparison
      echo "Yes";
}

文档:http://php.net/manual/en/function.strcasecmp.php

我的假设:-(你的文本文件看起来像这样)

moizhusnain@hotmail.com
dfgfdgmoizhusnain111@hotmail.com
moidgdfdffdgzhusnain@hotmail.com
moizdsfdsfdsdfhusnain@hotmail.com

按上述假设代码应为:-

<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
$toSearch="moizhusnain@hotmail.com";
$textData = file('text.txt',FILE_IGNORE_NEW_LINES); // use file() function with ignoring new lines of your text file
foreach($textData as $textDat){ // use foreach() rather than for() loop
  if ($toSearch == $textDat){
    echo "Yes";
  }
}
?>
参考

: -

http://php.net/manual/en/function.file.php

注意:-如果这对你有效,那只是意味着你的文本文件的新行限制了你的代码的工作,以及strcmp()实际上是不需要的。

虽然jonju已经做了一个使用另一种方法修复问题的工作示例,但它可以通过现有代码修复,只需使用这个RegEx(从这里偷来的)

$string = trim(preg_replace('/'s's+/', ' ', $string));

下面的代码可以工作:

<?php
$toSearch="moizhusnain@hotmail.com";
$textData=array();
$fla=FALSE;
$file=fopen('text.txt','r') or die('Unable to open file.');
while(!feof($file))
{
  $textData[]=trim(preg_replace('/'s's+/', ' ', fgets($file)));;
}
fclose($file);
for($i=0;$i<count($textData);$i++)
{
    if (strcmp($toSearch,$textData[$i])==0)
    {
        echo "Yes";
    }
}
?>