Reputation: 1
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 . ";\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;
}
}
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
Upvotes: -1
Views: 70
Reputation: 1092
change
fwrite($myfile, "user_id" . $user_id . " " . "chat_name" . $chat_name . ";\n");
to
fwrite($myfile, "user_id" . $user_id . " " . "chat_name" . $chat_name . ";");
The \n
represents a new line.
Upvotes: 2
Reputation: 1178
notice when you are writing file (fwrite) you are appending a "/n" char which is a new line char. in order to remove new line char you just need to remove that "/n" from your fwrite function
Upvotes: 1