簡體   English   中英

在特定行之后將字符串添加到文件

[英]add string to file after a specific line

我想知道是否有一種方法可以在php中的特定行之后將字符串添加到文件中? 我努力了

file_put_contents

但是它將字符串放在文件的末尾。 謝謝您的幫助。

已經有很長的時間了,但是將來對遇到這個問題的任何人都會有用...

$f = fopen("path/to/file", "r+");

$oldstr = file_get_contents("path/to/file");
$str_to_insert = "Write the string to insert here";
$specificLine = "Specify the line here";


// read lines with fgets() until you have reached the right one
//insert the line and than write in the file.


while (($buffer = fgets($f)) !== false) {
    if (strpos($buffer, $specificLine) !== false) {
        $pos = ftell($f); 
        $newstr = substr_replace($oldstr, $str_to_insert, $pos, 0);
        file_put_contents("path/to/file", $newstr);
        break;
    }
}
fclose($f);

這是一種方法,有點冗長,但是可以內聯進行所有修改:

$f = fopen("test.txt", "tr+");

// read lines with fgets() until you have reached the right one

$pos = ftell($f);                   // save current position
$trailer = stream_get_contents($f); // read trailing data
fseek($f, $pos);                    // go back
ftruncate($f, $pos);                // truncate the file at current position
fputs($f, "my strings\n");          // add line
fwrite($f, $trailer);               // restore trailing data

如果文件特別大,則需要一個中間文件。

一種方法是使用file()函數。 In返回每行該特定文件內容的數組。 從那里,您可以操縱數組並將該值附加到該特定行上。 考慮以下示例:

// Sample file content (original)
// line 1
// line 2
// line 3
// line 4
// line 5
// line 6


$replacement = "Hello World";
$specific_line = 3; // sample value squeeze it on this line
$contents = file('file.txt', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
if($specific_line > sizeof($contents)) {
    $specific_line = sizeof($contents) + 1;
}
array_splice($contents, $specific_line-1, 0, array($replacement)); // arrays start at zero index
$contents = implode("\n", $contents);
file_put_contents('file.txt', $contents);

// Sample output
// line 1
// line 2
// Hello World
// line 3
// line 4
// line 5
// line 6

以下是我的代碼

 function doit($search,$file,$insert)
{
$array = explode("\n", file_get_contents($file));
$max=count($array);
for($a=0;$a<$max;$a++)
{if($array[$a]==$search) {
$array = array_slice($array, 0, $a+1, true) +
array($insert) +
array_slice($array, $a+1);
 break;}}
 $myfile = fopen($file, "w");
 $max=count($array);
 var str='';
 for($a=0;$a<$max;$a++)
 {str.=$array[$a].'\n';}
 fclose($myfile);
 }

您必須提供$file路徑( $file ),新行文本( $insert )和行文本( $search ),然后在該行之后插入新行

暫無
暫無

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

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