简体   繁体   中英

add string to file after a specific line

I would like to know is there is a way to add string to a file after a specific line in php? I have tried

file_put_contents

but it puts the string at the end of the file. Thanks for the help.

Has been a long time but will be useful to anyone who come across this in future...

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

This is one approach, kinda verbose, but makes all modifications inline:

$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

If the file is particularly big, you would need an intermediate file.

Also one way is to use file() function. In returns an array of the contents of that particular file per line. From there, you can manipulate the array and append that value on that specific line. Consider this example:

// 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

The following is my code

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

You have to give the filepath ( $file ), the new line text ( $insert ) and the text of the line( $search ) after which the new line is to be inserted

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM