如何为PHP保存到文本文件的textarea消息添加分隔符?
解决文本追加时内容拼接的问题
问题说明
现有一段PHP代码可将textarea的输入内容保存到文本文件,但连续提交的消息会首尾拼接。例如:
- 第一次提交内容:
Hello How are you Good bye
- 第二次提交内容:
Let me upload this. Inform me if you receive it.
提交后文本文件内容变成:
Hello How are you Good byeLet me upload this. Inform me if you receive it.
需要调整代码,让每条消息末尾添加换行符及分隔符(如*************)。
修改后的PHP代码
<?php $filename = 'posts.txt'; $msg = isset($_POST['msg']) ? $_POST['msg'] : null; // 仅当有提交内容时才执行写入操作 if ($msg && is_writable($filename)) { // 添加分隔符和换行:在消息末尾追加换行+分隔符+换行 $contentToWrite = $msg . "\n*************\n"; if (!$handle = fopen($filename, 'a')) { echo "Cannot open file ($filename)"; exit; } if (fwrite($handle, $contentToWrite) === FALSE) { echo "Cannot write to file ($filename)"; exit; } echo "Success, wrote your message to file ($filename)"; fclose($handle); } elseif (!$msg) { echo "Please enter a message first."; } else { echo "The file $filename is not writable"; } ?>
修改要点
- 添加内容分隔符:将原代码中直接写入
$msg改为写入$msg . "\n*************\n",确保每条消息结束后添加换行和分隔线,彻底避免和下一条消息拼接。 - 增加空内容判断:新增
$msg非空的判断,避免写入空内容到文件中,减少无效操作。 - 优化提示信息:移除原提示中的
($msg),避免页面输出大量提交内容,提示更简洁友好。
表单代码(无需修改)
<form id="post" name="post" action="storeText.php" method="post"> <textarea cols="x" rows="x" name="msg"></textarea> <input class="button" type="submit" value="POST!"/> </form> <div class="menuItem" > <?=$msg?> </div>
内容的提问来源于stack exchange,提问作者Dhirgham Murran
相关产品推荐
相关产品推荐

