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]
Insert text to particular position in a file
Moderator: General Moderators
-
ashlythomas
- Forum Newbie
- Posts: 3
- Joined: Tue Jun 08, 2010 2:08 am
- phdatabase
- Forum Commoner
- Posts: 83
- Joined: Fri May 28, 2010 10:02 am
- Location: Fort Myers, FL
Re: Insert text to particular position in a file
Any reason you couldn't do this?
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.
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
If it's already in a file then explode on the newline "\n", reassemble using foreach and inject line at appropriate time.
- AbraCadaver
- DevNet Master
- Posts: 2572
- Joined: Mon Feb 24, 2003 10:12 am
- Location: The Republic of Texas
- Contact:
Re: Insert text to particular position in a file
Read the file into an array using file(), then you add to the end with:
Or you could just use file_put_contents() to append the line to the file.
You can add at a specific position with:
Then write it back out with file_put_contents():
Code: Select all
$lines[] = 'last line';You can add at a specific position with:
Code: Select all
array_splice($lines, 6, 0, 'line7');mysql_function(): WARNING: This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQLextension should be used. See also MySQL: choosing an API guide and related FAQ for more information.
-
ashlythomas
- Forum Newbie
- Posts: 3
- Joined: Tue Jun 08, 2010 2:08 am
Re: Insert text to particular position in a file
@AbraCadaver: Thanks a Million for the very nice solution.. that works now...
@phdatabase: i cannot change the text format in the file..
@phdatabase: i cannot change the text format in the file..