
<?php
/*
* $filepath檔案的路徑,
* $string要寫入的字元串,
* $line要插入、更新、删除的行數,
* $mode指定是插入(w)、更新(u)、删除(d)
*/
function fileline($filepath, $string, $line, $mode = 'w') {
if (is_file ( $filepath )) {
$filearr = file ( $filepath ); //把檔案存進數組
} else {
return '檔案不存在';
}
$size = count ( $filearr ); //數組的長度
if ($line > $size) { //如果插入的行數大于檔案現有的行數,直接用系統自帶的就行
return;
for($i = 0; $i < $size; $i ++) {
if ($i == $line - 1) {
switch (strtolower ( $mode )) { //判斷是寫入,還是删除或者是更新
case 'w' :
$newfilestr .= $string . "\r\n";
$newfilestr .= $filearr [$i];
case 'u' :
case 'd' :
continue;
}
} else {
$newfilestr .= $filearr [$i];
}
file_put_contents ( $filepath, $newfilestr );
return true;
}
//調用執行個體
fileline('w.txt','wwwww',1,'d');
?>