What best practices should be followed when replacing line breaks in PHP to ensure proper formatting in a textarea?

When replacing line breaks in PHP for proper formatting in a textarea, it is important to use the PHP function nl2br() to convert newline characters to HTML line breaks. This ensures that the text will be displayed correctly with line breaks in the textarea. Additionally, it is recommended to use htmlspecialchars() to escape any special characters to prevent XSS attacks.

$text = $_POST['textarea_input']; // Get the input from the textarea
$text = htmlspecialchars($text); // Escape special characters
$text = nl2br($text); // Convert newline characters to HTML line breaks
echo $text; // Display the formatted text in the textarea