ICC WORLD CUP 2011 WATCH LIVE ONLINE

How to remove line matching with string "Y" in a file using PHP

4:22 PM Posted by: Isuru Jayathissa 0 comments

//if you are call :
//delete_line
_string("you want to remove text" , "sometxtfile.txt");
//here delete 3rd line in
sometxtfile.txt file

function delete_line_string($find, $file)
{
$contents = array();
$new_contents = "";
$find = trim($find);
$return = false;

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

// loop through each line and see if it's the one we want

foreach($contents as $line_number => $line)
{
$lowercase_line = strtolower($line);
$lowercase_find = strtolower($find);
if($lowercase_line == $lowercase_find)
{
// this is where we remove the line
unset($contents[$line_number]);
$return = true;
}
}

// 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'))
{
trigger_error("$file could not be opened for writing", E_USER_NOTICE);
return false;
}
else
{

if(fwrite($handle, $new_contents) !== false)
{
// it worked
return $return;
}
}
}
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