php 删除 txt文本的任意一行
思路:
- 读入文件转换成数组
- unset数组相应的一项
- 最后写回文件
code:
function delLineFromFile($fileName, $lineNum){
// check the file exists
if(!is_writable($fileName))
{
// print an error
print “The file $fileName is not writable”;
// exit the function
exit;
}
else
{
// read the file into an array
$arr = file($fileName);
}
// the line to delete is the line number minus 1, because arrays begin at zero
$lineToDelete = $lineNum-1;
// check if the line to delete is greater than the length of the file
if($lineToDelete > sizeof($arr))
{
// print an error
print “You have chosen a line number, [$lineNum], higher than the length of the file.”;
// exit the function
exit;
}
//remove the line
unset($arr["$lineToDelete"]);
// open the file for reading
if (!$fp = fopen($fileName, ‘w+’))
{
// print an error
print “Cannot open file ($fileName)”;
// exit the function
exit;
}
// if $fp is valid
if($fp)
{
// write the array to the file
fwrite($fp,join($arr)); //foreach($arr as $line) { fwrite($fp,$line); } 之前是一个foreach,现在修改先join在一次写入
// close the file
fclose($fp);
}
echo “done”;
}