簡體   English   中英

寫入PHP中的特定行

[英]Write to specific line in PHP

我正在寫一些代碼,我需要在特定行上寫一個數字。 這是我到目前為止的內容:

<?php

$statsloc = getcwd() . "/stats/stats.txt";
$handle = fopen($statsloc, 'r+');

for($linei = 0; $linei < $zone; $linei++) $line = fgets($handle);
$line = trim($line);
echo $line;

$line++;
echo $line;

我不知道此后該繼續哪里。 我需要將$ line寫入該行,同時保留所有其他行。

您可以使用file將文件獲取為行的數組,然后更改所需的行,然后將全部重新寫回到文件中。

<?php
$filename = getcwd() . "/stats/stats.txt";
$line_i_am_looking_for = 123;
$lines = file( $filename , FILE_IGNORE_NEW_LINES );
$lines[$line_i_am_looking_for] = 'my modified line';
file_put_contents( $filename , implode( "\n", $lines ) );

這應該工作。 如果文件太大,它將變得效率很低,因此,這是否是一個好的答案取決於您的情況。

$stats = file('/path/to/stats', FILE_IGNORE_NEW_LINES);   // read file into array
$line = $stats[$offset];   // read line
array_splice($stats, $offset, 0, $newline);    // insert $newline at $offset
file_put_contents('/path/to/stats', join("\n", $stats));    // write to file

我今天遇到了這個問題,想使用發布的2個答案來解決,但這沒有用。 我不得不將其更改為:

<?php
$filepathname = "./stats.txt";
$target = "1234";
$newline = "after 1234";

$stats = file($filepathname, FILE_IGNORE_NEW_LINES);   
$offset = array_search($target,$stats) +1;
array_splice($stats, $offset, 0, $newline);   
file_put_contents($filepathname, join("\n", $stats));   
?>

由於這些行不起作用,因為數組的arg不是索引:

$line = $stats[$offset]; 
$lines[$line_i_am_looking_for] = 'my modified line';

必須添加+1才能在搜索到的文本下添加新行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM