donglei2022 2018-12-01 09:29
浏览 16

删除换行符时出现问题

I've tried everything I could think of yet I still couldn't get the code to delete the new line character that is appended at each new entry.

if ($_POST['what_to_do']==1){
    if ((isset($_POST['chat_name'])) and ($_POST['chat_name']!=NULL)){
        $chat_name=$_POST['chat_name'];
        $myfile = fopen("users.txt", "a");
        fwrite($myfile, "user_id" . $user_id . " " . "chat_name" . $chat_name . ";
");
        fclose($myfile);
        $_SESSION['is_chat_logged'] = 1;
    }
}
elseif ($_POST['what_to_do']==2){
    if ($_SESSION['is_chat_logged'] = 1){
            $actual_file=file_get_contents("users.txt");
            $position_start=strpos($actual_file, "user_id" . $user_id . " ");
            $line=file_get_contents("users.txt",FALSE,NULL,$position_start);
            $position_end=strpos($line, ";")+1+$position_start;
            $part_to_be_replaced=substr($actual_file, $position_start, $position_end-strlen($actual_file));
            $new_actual_file= str_replace($part_to_be_replaced, "", $actual_file);
            $myfile = fopen("users.txt", "w");
            fwrite($myfile, $new_actual_file);
            fclose($myfile);
        $_SESSION['is_chat_logged'] = 0;
    }
}

The users.txt looks like this:

user_id1 chat_nameJake;
user_id2 chat_nameSomeone;
user_id43 chat_nameZeke;
user_id22 chat_nameBilly;

Any help would be appreciated.


EDIT: I've found out what the problem was. I was using the substr() function the wrong way. Instead of $position_end-strlen($actual_file) I should have put $position_end-$position_start+1

  • 写回答

2条回答 默认 最新

  • doushi1929 2018-12-01 09:33
    关注

    change

    fwrite($myfile, "user_id" . $user_id . " " . "chat_name" . $chat_name . ";
    ");
    

    to

    fwrite($myfile, "user_id" . $user_id . " " . "chat_name" . $chat_name . ";");
    

    The represents a new line.

    评论

报告相同问题?

悬赏问题

  • ¥50 树莓派安卓APK系统签名
  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗