Reputation: 120
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="[email protected]";
$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";
}
}
Upvotes: 2
Views: 1116
Reputation: 72269
My Assumption:-(your text file looks like this)
[email protected]
[email protected]
[email protected]
[email protected]
According to above assumption code should be:-
<?php
error_reporting(E_ALL);
ini_set('display_errors',1);
$toSearch="[email protected]";
$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";
}
}
?>
Reference:-
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.
Upvotes: 2
Reputation: 11182
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)
$string = trim(preg_replace('/\s\s+/', ' ', $string));
The following code works:
<?php
$toSearch="[email protected]";
$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";
}
}
?>
Upvotes: 0
Reputation: 2736
Try this
if (strcasecmp ($toSearch,$textData[$i])==0){ //case insensitive comparison
echo "Yes";
}
Doc: http://php.net/manual/en/function.strcasecmp.php
Upvotes: 3