Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

replacing a line of text in a text file

Status
Not open for further replies.

c0deM0nK424

Programmer
Oct 28, 2007
126
GB
any tips on the best and simplest way to replace a line of text in a text file ? this could mean anywhere in the file, i.e 1st line, 15th line, 59th line etc.

i have a function buts its far too long and tedious i feel. other suggestions would be helpful.
 
Code:
function replaceline($search, $replace, $file){
 if (!is_file($file)){
  die('not a file');
 }
 $fileContents = file_get_contents($file);
 $pattern = '/^\\s*'.$search.'\\s*$/';
 $fileContents = preg_replace($pattern, $replace, $fileContents,null,$count);
 if ($count > 0){
  file_put_contents($file);
 }
}

note that this works for a case sensitive whole line search and replace only.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top