Page 1 of 1

Insert text to particular position in a file

Posted: Tue Jun 08, 2010 2:30 am
by ashlythomas
Hi friends,

I am a newbie in string functions in php. I have a text file which contains some lines of text in a particular format.
I am using php to maniputlate this text file.

[text]
Text1 = This is my first line of text
Text2 = This is my second text
Text3 = This is my third text
Text5 = This is fifth line of text
Text10 = This is tenth line in the file
....
....[/text]

I would like to insert some missing text at the end or in between the existing lines. For example, I would like to write Text7 in the file in the exact place now. Can anyone please give me a solution for this?

After the insertion, the file should look like this:


[text]Text1 = This is my first line of text
Text2 = This is my second text
Text3 = This is my third text
Text5 = This is fifth line of text
Text7 = This is seventh line in the file
Text10 = This is tenth line in the file
....
....[/text]

Re: Insert text to particular position in a file

Posted: Tue Jun 08, 2010 8:30 am
by phdatabase
Any reason you couldn't do this?

Code: Select all

Text[1] = This is my first line of text
Text[2] = This is my second text
Text[3] = This is my third text
Text[5] = This is fifth line of text
Text[10] = This is tenth line in the file
Then the solution becomes obvious
If it's already in a file then explode on the newline "\n", reassemble using foreach and inject line at appropriate time.

Re: Insert text to particular position in a file

Posted: Tue Jun 08, 2010 10:17 am
by AbraCadaver
Read the file into an array using file(), then you add to the end with:

Code: Select all

$lines[] = 'last line';
Or you could just use file_put_contents() to append the line to the file.

You can add at a specific position with:

Code: Select all

array_splice($lines, 6, 0, 'line7');
Then write it back out with file_put_contents():

Re: Insert text to particular position in a file

Posted: Tue Jun 08, 2010 11:41 pm
by ashlythomas
@AbraCadaver: Thanks a Million for the very nice solution.. that works now...

@phdatabase: i cannot change the text format in the file..