-1

my code is,

<?php 

$data = file_get_contents('file.conf');
$rows = explode("\n", $data);
$rcount = count($rows); 
echo $rcount;
for ($l=0; $l<$rcount; $l++)
{
    $rowss = $rows[$l];
    if ($rowss == "[default]")
    {
        file_put_contents($rowss, "\nhi", FILE_APPEND | LOCK_EX) or die("<br>oops");
    }
}


?>

output is,

52
oops

and my file(file.conf) contains 52 rows that is printed successfully, but cant write on that file

i need to add some string like "hi" to the end of "[default]" line

example, my file is

eastern=America/New_York|'vm-received' Q 'digits/at' IMp
central=America/Chicago|'vm-received' Q 'digits/at' IMp
central24=America/Chicago|'vm-received' q 'digits/at' H N 'hours'
military=Zulu|'vm-received' q 'digits/at' H N 'hours' 'phonetic/z_p'
european=Europe/Copenhagen|'vm-received' a d b 'digits/at' HM



[default]

1234 => 4242,Example Mailbox,root@localhost
;4200 => 9855,Mark Spencer,markster@linux-    support.net,[email protected],attach=no|[email protected]|tz=central|maxmsg=    10
;4300 => 3456,Ben Rigas,[email protected]
;4310 => -5432,Sales,[email protected]

pls help me

thank u

1 Answer 1

1

Let's assume you want to add 2 lines after line 20.

You can use array_splice:

$newlines = [ 'first line', 'second line' ];
array_splice($rows, 20, 0, $newlines);

The $newlines array can contain as many lines as you want to add. You can also just add one line, but it has to be in an array so that array_splice can use it.

So in your example you could use:

if ($rowss == "[default]")
{
    $newlines = [ 'first line', 'second line' ];
    array_splice($rows, $l + 1, 0, $newlines);
}

This will get the line with [default], and add the lines after it ($l + 1 is the current line, containing [default]).

Not the answer you're looking for? Browse other questions tagged .