Insert string in to known position of text

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Kind-Wizzard
Forum Newbie
Posts: 7
Joined: Thu Sep 10, 2009 11:59 am
Location: Moon

Insert string in to known position of text

Post by Kind-Wizzard »

Help me please. And sorry for my bed english :roll: .
I wan't to insert a few lines in to the text file (size about 1MB), at known position, but i did not found special function. Should i use replace functions?

And addition for those who can understand my english :)
There is a fairly large text file (size about 1 MB) in this file i want to insert a few lines (not in the end), then save the new file. File updates more than once. So I decided that the smallest server load will be, if not to replace one piece of string the new line, simply insert a new line in the source file at know pos.
But reading the features, I realized that the special function to insert a row in a certain position - no. So the question may be all I did was wrong? Maybe there is such a function, help to be more competently implement the decision.
Last edited by Kind-Wizzard on Thu Sep 10, 2009 1:37 pm, edited 1 time in total.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Insert string in to known position of text

Post by requinix »

You can't insert into a file - just overwrite.

The simplest way to do this would be

Code: Select all

$contents = file_get_contents("/path/to/file");
$new_contents = substr($contents, 0, 100) . "inserted text" . substr($contents, 100);
file_put_contents("/path/to/file", $new_contents);
where 100 is the offset (100th character) where the new text should be inserted.
Kind-Wizzard
Forum Newbie
Posts: 7
Joined: Thu Sep 10, 2009 11:59 am
Location: Moon

Re: Insert string in to known position of text

Post by Kind-Wizzard »

Thanks!
Post Reply