dsfdsf23423 2016-03-08 11:38
浏览 76
已采纳

删除一行并替换为txt文件中的新文本

i have a txt file containing 20 lines i want to replace line # 4 with a new text from an input ...i have tried this and some others but not solving my problem. PHP Code

<?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>

what i want i want to select a value from drop-down list (line #) and that whole line will be replace with the new text.

  • 写回答

1条回答 默认 最新

  • doqo89924 2016-03-08 11:54
    关注

    try below solution also make sure file have write permission:

    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."
    ";
        $file_content = implode("", $file_array);
        $f = fopen($selected_file, 'w+') or die('unable to open');
        fwrite($f, $file_content);
        fclose($f);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 请问如何在openpcdet上对KITTI数据集的测试集进行结果评估?
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错