What potential pitfalls can arise when using nl2br in PHP for formatting text with line breaks?

Using nl2br in PHP to format text with line breaks can potentially introduce security risks such as allowing malicious code to be injected into the output. To prevent this, it is important to properly sanitize the input before applying nl2br. One way to do this is by using the htmlspecialchars function in conjunction with nl2br to ensure that any HTML tags are rendered as plain text.

$input = "<script>alert('Hello');</script>\nThis is a test.";
$sanitized_input = htmlspecialchars($input, ENT_QUOTES, 'UTF-8');
$formatted_text = nl2br($sanitized_input);

echo $formatted_text;