ICC WORLD CUP 2011 WATCH LIVE ONLINE

How to DELETE n th line in a file using PHP

4:14 PM Posted by: Isuru Jayathissa 0 comments

function delete_line_by_number($line, $file)
{
$contents = array();
$new_contents = "";
$number_of_lines = 0;

if(file_exists($file))
{
if(is_writable($file))
{
// open the file as an array, each line as an element
if($contents = file($file))
{
$number_of_lines = count($contents);
if($line <= $number_of_lines)
{
// remove extra whitespace from each line
$contents = array_map("trim", $contents);

// remove the line in question
unset($contents[($line-1)]);

// put the lines back together with a \n between each
$new_contents = implode("\n", $contents);

// open the file and delete its old contents
if($handle = fopen($file, 'w'))
{
if(fwrite($handle, $new_contents) !== false)
{
// it worked
return true;
}
}
else
{
trigger_error("$file could not be opened for writing", E_USER_NOTICE);
return false;
}
}
else
{
trigger_error("$file only has $number_of_lines lines, so line $line could not be removed", E_USER_NOTICE);
return false;
}
}
else
{
trigger_error("$file is not readable", E_USER_NOTICE);
return false;
}
}
else
{
trigger_error("$file is not writable", E_USER_NOTICE);
return false;
}
}
else
{
trigger_error("$file does not exist", E_USER_NOTICE);
return false;
}

No comments:

Post a Comment

 


2009 Isuru's Blog. All rights reserved.
.
For the more details..,
keijayathissa@gmail.com