[英]String Comparison in php is not working
I am trying to open a file and compare each line to a string to see if they are same or not, but it's not working, here is the code. 我正在尝试打开一个文件,并将每一行与一个字符串进行比较,以查看它们是否相同,但是它不起作用,这是代码。
$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";
}
}
Try this 尝试这个
if (strcasecmp ($toSearch,$textData[$i])==0){ //case insensitive comparison
echo "Yes";
}
Doc: http://php.net/manual/en/function.strcasecmp.php Doc: http : //php.net/manual/en/function.strcasecmp.php
What i have assumed and what code you have to do is given below:- 我假设了什么,你要做的代码如下:
Assumption:-(your text file looks like this) 假设:-(您的文本文件如下所示)
moizhusnain@hotmail.com
dfgfdgmoizhusnain111@hotmail.com
moidgdfdffdgzhusnain@hotmail.com
moizdsfdsfdsdfhusnain@hotmail.com
So code should be:- 所以代码应该是:
<?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
echo "<pre/>";print_r($textData); // print array
foreach($textData as $textDat){ // use foreach() rather than for() loop
if ($toSearch == $textDat){
echo "Yes";
}
}
?>
Reference:- 参考:-
http://php.net/manual/en/function.file.php http://php.net/manual/en/function.file.php
Note:- If this works for you that simply means that new lines of your text-file are restricting your code to work as well as strcmp()
is not needed actually. 注意:-如果这对您有效,则仅意味着文本文件的新行限制了代码正常工作,并且实际上不需要
strcmp()
。
While jonju has made a working example that fixes the problem using another approach, it can be fixed with the existing code, merely by using this RegEx ( stolen from here ) 尽管jonju给出了使用其他方法解决问题的可行示例,但仅使用此RegEx( 从此处偷来的 ),就可以使用现有代码对其进行修复。
$string = trim(preg_replace('/\s\s+/', ' ', $string));
The following code works: 以下代码有效:
<?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";
}
}
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.