如何在每行的开头附加数字 [PHP]


How to append number at the beginning of each line [PHP]?

我有测试.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|"?

为此,

您需要逐行读取文件。你可以在一段时间内做到这一点,就像这样

$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);

这样的事情应该能够完成你想要的。
我没有测试它,所以你可能需要改变一些东西。