Reputation: 21
I want to pass the string returned by reading a file line by line into a function. But its givin an unusual error.Seems as if the string returned is not exactly the line in the .txt file(source file).However if i manually pass strings into the function by copy pasting it works.heres ma code:-
<?php
function check($string) { // for removing certain text from the file
$x = 0;
$delete = array();
$delete[0] = "*";
$delete[1] = "/";
for($i=0;$i<2;$i++){
$count=substr_count($string,$delete[$i]);
if($count>0){
$x++;
return false;
break;
}
}
if($x==0)return true;
}
$file = fopen("classlist.txt", "r") or die("Unable to open file!");
$myFile = "new.txt";
$fh = fopen($myFile, "w") or die("can't open file");
while(!feof($file)){
if(check(fgets($file))){
$stringData = fgets($file);
fwrite($fh, $stringData);
}
}
fclose($fh);
?>
what i get on ma new.txt file is:line 2 line 4 line 6 line8---------- line 21 Plz help me out.....
Upvotes: 2
Views: 388
Reputation: 197757
You could rewrite your code so that you reduce the places where errors can occur, the SplFileObject
is handy to operate with textfiles and to go over each line.
A FilterIterator
can be used to only return those lines that do not contain *
or /
.
Example:
<?php
$inFile = "classlist.txt";
$myFile = "new.txt";
$outFile = new SplFileObject($myFile, 'w');
class LineFilter extends FilterIterator
{
public function accept()
{
$line = $this->getInnerIterator()->current();
return strlen($line) === strcspn($line, '*/');
}
}
$filteredLines = new LineFilter(new SplFileObject($inFile));
foreach($filteredLines as $line)
{
$outFile->fwrite($line);
}
?>
Upvotes: 0
Reputation: 3717
The while loop should look something more like this:
while(!feof($file)){
$stringData = fgets($file);
if(check($stringData)){
fwrite($fh, $stringData);
}
}
Because you're calling fgets twice, you're checking odd lines and writing out even lines.
Upvotes: 2
Reputation: 798626
Each call to fgets()
retrieves a new line from the file. Call it once per loop iteration, putting the returned line in a variable, and then check and use that variable.
Upvotes: 2