PHP – replace line in a file

The Task

Now I am working with drupal. For some reason I had a requirement to change some particular lines using the line numbers.
Say, I have a css file. Line number I need to change line number 2, 6 and 9. I made a script to do that. This is how this works…

The idea and development

Using file() function we can get each line in array format [$lines = file($file_path)]. To change line number 2 we do [$lines[1] = “background: #ECECEC;”. After that we can implode() the array and change the content of the file using fwrite() function.

Consider the following css file (style.css)

.header {
	background: #EFEFEF;
	color: #000000;
}
.title {
	color: #FFFFFF;
}
.footer {
	color: #000000;
}

If we use,

$lines = file(‘style.css’);
$lines[1] = “background: #ECECEC”;
$new_content = implode('', $lines);
$h = fopen(‘style.css’, 'w'));
fwrite($h, $new_content));
fclose($h);

The css file will be,

.header {
background: # ECECEC;color: #000000;
}
.title {
	color: #FFFFFF;
}
.footer {
	color: #000000;
}

What we are missing is a tab in front of the content and a line break at the end.
So we can change the replace code as,

$lines[1] = chr(9); . “background: #ECECEC” . chr(13) . chr(10);

Done. This is the actual process. Using this method I have made the following function to change some lines in a single call.

<?php
	function replace_lines($file, $new_lines, $source_file = NULL) {
		$response = 0;
		//characters
		$tab = chr(9);
		$lbreak = chr(13) . chr(10);
		//get lines into an array
		if ($source_file) {
			$lines = file($source_file);
		}
		else {
			$lines = file($file);
		}
		//change the lines (array starts from 0 - so minus 1 to get correct line)
		foreach ($new_lines as $key => $value) {
			$lines[--$key] = $tab . $value . $lbreak;
		}
		//implode the array into one string and write into that file
		$new_content = implode('', $lines);

		if ($h = fopen($file, 'w')) {
			if (fwrite($h, $new_content)) {
				$response = 1;
			}
			fclose($h);
		}
		return $response;
	}
?>

How to use

Consider the above css file.
To change some lines in that file use this:

$new_lines = array(2 => ‘background: #ECECEC’, 6 => ‘background: #F8F8F8’, 9 => ‘background: #FFF);
replace_lines(‘style.css’, $new_lines);

To copy style.css into a new file with some change:

if(replace_lines(‘style.css’, $new_lines, ‘new_style.css’)) {
	print “File successfully updated”;
}
else {
	print “File update failed.”;
}

Enjoy 🙂
-Beschi A.

This entry was posted in PHP, Tutorial and tagged , , , , , . Bookmark the permalink.

1 Response to PHP – replace line in a file

Leave a comment