如何跳过x行的fwrite()

时间:2016-06-29 12:11:59

标签: php iteration

我正在创建PHP程序,它应该在* .txt文件行中找到以单词“tak”开头并跳过该程序将其重写为下一个* .txt文件。所以我现在想要实现的是阻止它写入,例如,以“tak”字开头的另外两行。这是我的代码:

<?php
$file2 = fopen("out.txt", "w") or die("Unable to open file!");
$handle = fopen("plik.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        if (strpos($line, 'tak') === 0) {
            echo 'found<br/>';
        }
        else {
            fwrite($file2, $line);
        }
    }
    fclose($handle);
    echo 'OK';
}
else {
    echo "can't read the file";
}

?>

2 个答案:

答案 0 :(得分:1)

我认为使用filefor循环和file_put_contents会更有效。

$file2 = "out.txt";
//$file = file($file2) or die("Unable to open file!");
$file = array('asdf',
'asdf',
'asdf',
'tak',
'1',
'2',
'3',
'4');
file_put_contents($file2, ''); // truncate file;
for($i = 0; $i < count($file); $i++) {
    $line = $file[$i];
    if (strpos($line, 'tak') === 0) {
        echo 'found<br/>';
        $i = $i + 2;
    } else {
  //     file_put_contents($file2, $line, FILE_APPEND | LOCK_EX);
       echo $line;
    }
    echo 'ok';
}

演示:https://eval.in/597694

输出(有点混乱但得到点tak12已跳过):

asdfokasdfokasdfokfound<br/>ok3ok4ok

答案 1 :(得分:0)

您可以通过保留booleaninteger变量来计算出现次数。像这样,

<?php
$file2 = fopen("out.txt", "w") or die("Unable to open file!");
$handle = fopen("plik.txt", "r");
if ($handle) {
    $stopWriteLines=false;
    $max_line_skip=2;
    // Taking above two variables for our logic.

    while (($line = fgets($handle)) !== false) {
        if($stopWriteLines) {
            $max_line_skip--;   
        }
        // Above condition check if we found tak in line then decrements the skip lines count.

        if (strpos($line, 'tak') === 0) {
            echo 'found<br/>';
            $stopWriteLines=true; // Setting Boolean variable to skip writing lines.
        }
        else {
            if(!$stopWriteLines) { // will write only if Boolean variable is set to true.
                fwrite($file2, $line);
            }
        }

        if($max_line_skip==0) {
           $stopWriteLines=false;
        }

        // Above condition will make Boolean variable false after skipping 'n' lines.
    }
    fclose($handle);
    echo 'OK';
}
else {
    echo "can't read the file";
}
?>

请检查代码中的说明,以便更好地理解受尊重的代码部分。