我已经尝试了所有可能想到的方法,但仍然无法获得删除在每个新条目后附加的换行符的代码。
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 . ";\n");
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;
}
}
users.txt如下所示:
user_id1 chat_nameJake;
user_id2 chat_nameSomeone;
user_id43 chat_nameZeke;
user_id22 chat_nameBilly;
任何帮助将不胜感激。
编辑:我发现了问题所在。我以错误的方式使用了substr()函数。我应该把$ position_end- $ position_start + 1
代替$ position_end-strlen($ actual_file)答案 0 :(得分:3)
更改
fwrite($myfile, "user_id" . $user_id . " " . "chat_name" . $chat_name . ";\n");
到
fwrite($myfile, "user_id" . $user_id . " " . "chat_name" . $chat_name . ";");
\n
代表换行符。
答案 1 :(得分:2)
注意,在编写文件(fwrite)时,您将附加一个“ / n”字符,它是换行符。为了删除换行符,您只需要从fwrite函数中删除该“ / n”