更新和存储内容文本区域时如何避免中断

How to avoid breaks when content textarea is updated and stored

我正在使用文本区域,用户可以在其中放置一些内容并保存内容。 因此,一个文件,如 example.txt 及其内容将保存在服务器上。 会发生什么:即使用户不更改内容并更新它,textarea 的内容也会在内容之前保存几次中断。

下面我存储内容并读回的方式:

<form class="rafform" method="post">
    <input type="hidden" name="editfile" value="<?php echo $dir . '/' . $file; ?>" />
    <textarea name="editcontent">
       <?php
          readfile($dir . '/' . $file); // read content of example.txt         ?> 
    </textarea>
    <input type="submit" class="submitmodal edit btn btn-edit " value="Update" />
</form>

提交后,内容将被替换

if( isset($_POST['editcontent']) ){
$fn = $_POST['editfile'];   

$content = stripslashes($_POST['editcontent']);
$fp = fopen($fn,"w") or die ("Error opening file in write mode!");
fputs($fp,$content);
fclose($fp) or die ("Error closing file!");
echo 'Content edited!';
}

如果在第一行开始输入文字,它看起来像这样:

如果我更新此文本(因此存储它)并再次打开它,它看起来像这样:

所以:为什么文本前有几个分隔符和空格? (文本应该在左上角重新开始,因为我没有做任何更改)...

试试这个: 不要在 <textarea></textarea> 之间输入一些内容。 并使用 trim 函数

str.trim();


<form class="rafform" method="post">
    <input type="hidden" name="editfile" value="<?php echo $dir . '/' . $file; ?>" />
    <textarea name="editcontent"><?php
          readfile($dir . '/' . $file); // read content of example.txt         ?></textarea>
    <input type="submit" class="submitmodal edit btn btn-edit " value="Update" />
</form>

if( isset($_POST['editcontent']) ){
$fn = trim($_POST['editfile']);   

$content = stripslashes($_POST['editcontent']);
$fp = fopen($fn,"w") or die ("Error opening file in write mode!");
fputs($fp,$content);
fclose($fp) or die ("Error closing file!");
echo 'Content edited!';
}

尝试使用trim(); PHP 函数 https://www.w3schools.com/php/func_string_trim.asp 删除两边的任何空格