我想通过逐行读取文件将返回的字符串传递给函数。但是它给出了一个不寻常的错误。返回的字符串似乎不完全是.txt文件(源文件)中的行。然而,如果我手动通过复制粘贴将字符串传递到函数中,它就会起作用。下面是代码:-
<?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);
?>
我在ma new.txt文件上得到的是:第2行第4行第6行第8行----------第21行请帮帮我.....
对fgets()
的每个调用都从文件中检索一个新行。每次循环迭代调用一次,将返回的行放入变量中,然后检查并使用该变量。
while循环应该看起来像这样:
while(!feof($file)){
$stringData = fgets($file);
if(check($stringData)){
fwrite($fh, $stringData);
}
}
因为调用了两次fgets,所以检查的是奇数行,写出的是偶数行。
您可以重写代码,以便减少可能发生错误的地方,SplFileObject
可以方便地操作文本文件并遍历每一行。
使用FilterIterator
只返回不包含*
或/
的行。
的例子:
<?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);
}
?>