How can the str_replace() function be utilized to replace line break characters in a string before saving it to a .txt file in PHP?

When saving a string to a .txt file in PHP, line break characters (\n) may cause formatting issues. To replace these line breaks before saving the string, the str_replace() function can be used to replace "\n" with an empty string. This will ensure that the text is saved without any line breaks interfering with the formatting.

<?php
// Sample string with line breaks
$text = "This is a sample text\nwith line breaks";

// Replace line breaks with an empty string
$cleaned_text = str_replace("\n", "", $text);

// Save the cleaned text to a .txt file
$file = fopen("output.txt", "w");
fwrite($file, $cleaned_text);
fclose($file);
?>