代码之家  ›  专栏  ›  技术社区  ›  michaelmcgurk

循环浏览文本文件,修改并编写新文件

php
  •  0
  • michaelmcgurk  · 技术社区  · 5 年前

    我有个文件叫 test.txt . 它包含多行文本,如下所示:

    Test Data:
    Tester 2 Data:
    Tests 3 Data:
    

    我想有一个PHP脚本,打开这个文件,带字前的所有文本 Data: 并输出结果:

    Data:
    Data:
    Data:
    

    我的 菲律宾比索

    $myfile = fopen("test.txt", "r") or die("Unable to open file!");
    $data = fread($myfile,filesize("test.txt"));
    
    // foreach line do this
    $line = strstr($data,"Data:");
    //append $line to newtest.txt
    // endforeach
    
    fclose($myfile);
    
    1 回复  |  直到 5 年前
        1
  •  2
  •   Tigger    5 年前

    你可以用 file() 逐行打开和循环一个文件。

    因为你在移除之前的所有东西 Data: ,根据您提供的测试数据(这就是我要说的),我们只需要知道行数。所以,我们可以用 count()

    然后将新数据构造为变量,最后使用 file_put_contents()

    使用 trim()

    $raw = file("./test.txt");
    $lineCount = count($raw);
    $newFile = null;
    do {
        $newFile .= "Data:\r\n";
    } while(--$lineCount > 0);
    file_put_contents('./test-new.txt',trim($newFile));
    

    编辑: 别慌 在下面的评论中说,你可以使用 str_repeat() 甚至可以移除 do while

    这是那个版本 计数()

    $raw = file("./test.txt");
    $newFile = str_repeat("Data:\r\n",count($raw));
    file_put_contents('./test-new.txt',trim($newFile));