2016-03-08 151 views
-1

我有一個包含20行的txt文件,我想用輸入中的新文本替換行#4 ...我試過this和其他一些文件,但沒有解決我的問題。 PHP代碼刪除一行並用txt文件中的新文本替換

<?php 
if(isset($_POST['submit'])){ 

$selected_file = $_POST['files']; 
$line = $_POST['to_line']; 
$text = $_POST['text']; 


//opn file 
$file_open = fopen($selected_file,"r+") or die('Fail to open a file'); 
//fwrite($file_open,$text); 


$file_array = file($selected_file); 
$file_array[$line] = $text; 
$file_array = implode($file_array); 
file_put_contents($selected_file,$file_array); 

?> 

HTML

<form name="write" method="post" action=""> 
<table> 

<tr><td>Select File</td><td><select name="files" style="width:183px;"> 
<?php 



foreach ($a = scandir('.') as $file){ 
    $extension = pathinfo($file, PATHINFO_EXTENSION); 
    if($extension == 'txt' || $extension == 'doc'){ 
echo"<option>".$file."</option>"; 
}} 


?> 

></select></td></tr> 
<tr><td>Line</td><td><select name="to_line" style="width:183px"> 

<option>1</option> 
<option>2</option> 
<option>3</option> 
<option>4</option> 
<option>5</option> 
<option>6</option> 
<option>7</option> 
</select> 
</td></tr> 
<tr><td>Write Text</td><td><textarea name="text" style=" height:120px" ></textarea></td></tr> 
<tr><td></td><td><input type="submit" name="submit" value="Save" /></td></tr> 


</table> 
</form> 

我想要什麼 我要選擇從下拉列表中(行號),以及整條生產線的值將用新文本替換。

+0

確切部位在哪裏失敗?你調試過源代碼嗎? – RhinoDevel

+0

你有什麼問題? –

+0

它只是將文本添加到行的末尾。我想用新文字替換整行。 – Khan

回答

0

嘗試下面的解決方案還確保文件的寫權限:

if(isset($_POST['submit'])) { 

    $selected_file = $_POST['files']; 
    $line = $_POST['to_line']; 
    $text = $_POST['text']; 

    $file_array = file($selected_file); 
    $file_array[$line - 1] = $text."\n"; 
    $file_content = implode("", $file_array); 
    $f = fopen($selected_file, 'w+') or die('unable to open'); 
    fwrite($f, $file_content); 
    fclose($f); 
} 
+0

..你已經證明是最好的兄弟...但再次有點問題的一些時間它的工作和一些時間不,也是一個正方形出現在最後... – Khan

+0

可能是在您的文件中的一些特殊字符 –