Jump to content

Change a file with specific line


sniperscope

Recommended Posts

Hi all gurus,

How can i Edit or Delete of a file.

For example: i have an INI file something like below and i want to change it. Great appreciate if any help

 

Name = Example;

Age  = 33;              <--------------------- Want to change this line.

School = University;

Address = Japan;      <--------------------- Want to delete this line.

Phone = 0123-14544521;

And add a new line at the end of file, Replace Phone into PhoneNumber.

 

Regards

 

 

Link to comment
Share on other sites

You can load the file as an array (one line per element) using file. To delete a line you can just delete its element, and to change a line you can iterate over the array until you find the one you need (if it's a large file then you probably do not want to do this as this kind of searching will run in linear time). You can then join them together.

 

You could also use regular expressions to delete and edit.

Link to comment
Share on other sites

i would suggest file() to get the files information into an array...if that was all that was in your file...you would have

<?php

$fileName = 'somefile.ini';
$myInfo = file($fileName);

print_r($myInfo); //prints readable array of file info....eg..

/*
[0] = 'Name = Example;'
[1] = 'Age  = 33;'
[2] = 'School = University;'
[3] = 'Address = Japan;'
[4] = 'Phone = 0123-14544521;'
*/ 

 

 

then to edit the information you just use any applicable series of string functions like preg replace, or strstr...or just flat out replace the array value at what ever point...then to rewrite the data back onto the file just iterate through your array and use the fwrite function... :-)

 

http://us.php.net/file

http://us.php.net/fwrite

http://us.php.net/manual/en/function.preg-replace.php

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.