What best practices should be followed when dealing with line breaks in PHP text file manipulation?
When dealing with line breaks in PHP text file manipulation, it is important to use the correct line ending characters based on the operating system (e.g., "\n" for Unix/Linux, "\r\n" for Windows). This ensures that the text files are properly formatted and displayed across different platforms. Additionally, it is good practice to trim any extra whitespace or line breaks from the beginning and end of each line to avoid unexpected behavior.
// Read a text file and normalize line breaks
$file = 'example.txt';
$content = file_get_contents($file);
// Normalize line breaks based on the operating system
$content = str_replace("\r\n", "\n", $content); // Windows to Unix/Linux
$content = str_replace("\r", "\n", $content); // Mac to Unix/Linux
// Trim any extra whitespace or line breaks
$content = trim($content);
// Write the normalized content back to the file
file_put_contents($file, $content);