【问题标题】:How to append number at the beginning of each line [PHP]?如何在每行的开头附加数字[PHP]?
【发布时间】:2015-09-06 10:41:21
【问题描述】:

我有包含以下数据的 test.txt

2015-06-19 14:46:10 10 
2015-06-19 14:46:11 20 
2015-06-19 14:46:12 30

(这是自动生成的,无法编辑) 然后我使用以下 php 脚本写入名为 tempdata.txt 的临时文件

<?php
    $myFile = "filelocation/test.txt";
    $myTempFile = "filelocation/tempdata.txt";

    $string = file_get_contents($myFile, "r");
    $string = preg_replace('/\t+/', '|', $string);
    $fh = fopen($myTempFile, 'w') or die("Could not open: " . mysql_error());
    fwrite($fh, $string);
    fclose($fh);
?>

这使得 tempdata.txt 看起来像:

2015-06-19 14:46:10|10
2015-06-19 14:46:11|20
2015-06-19 14:46:12|30

但是我想在每行的开头添加行号,如下所示:

1|2015-06-19 14:46:10|10
2|2015-06-19 14:46:11|20
3|2015-06-19 14:46:12|30

有什么方法可以读取 php 中的行号并将其添加到每一行的前面,如“n|” ?

【问题讨论】:

    标签: php append


    【解决方案1】:

    为此,您需要逐行读取文件。 你可以像这样在一个while循环中做到这一点

    $count = 0;
    
    $myFile = "filelocation/test.txt";
    $myTempFile = "filelocation/tempdata.txt";
    
    $string = fopen($myFile, "r");
    $fh = fopen($myTempFile, 'w') or die("Could not open: " . mysql_error());
    
    while ($line = fgets($string)) {
         // +1 on the count var
         $count++;
    
         $line = preg_replace('/\t+/', '|', $line);
    
         // the PHP_EOL creates a line break after each line
         $line = $count . '|' . $line . PHP_EOL;
         fwrite($fh, $line);
    }
    
    fclose($fh);
    

    类似的东西应该能够完成你想要的。
    我没有对其进行测试,因此您可能需要更改一些内容。

    【讨论】:

    • Line 15: Unexpected '{' at: while (($line = fgets($string)) { 虽然你打开了 while 循环这很奇怪..
    • @MieerDarwesh 我更改了我的代码((而不是(在开头>。
    • haha :p 这个问题已经解决了,但是它确实说:fgets() 期望参数 1 是资源,字符串在.. 在第 16 行给出:while ($line = fgets ($string))
    • @MieerDarwesh 啊,是的,你应该使用 fopen 我再次更改代码
    • 谢谢老兄(dankjewel)
    猜你喜欢
    • 2016-08-06
    • 2013-08-06
    • 2018-10-30
    • 2011-05-26
    • 1970-01-01
    • 1970-01-01
    • 2011-04-15
    • 1970-01-01
    相关资源
    最近更新 更多