What is the purpose of using nl2br() in PHP and what are the potential pitfalls when using it to convert line breaks to HTML line breaks?

The purpose of using nl2br() in PHP is to convert newline characters (\n) into HTML line breaks (<br>). This is commonly used when displaying text from a database or textarea input on a webpage to ensure that line breaks are preserved. However, a potential pitfall when using nl2br() is that it can lead to double line breaks if the input already contains HTML line breaks. To avoid this issue, it's important to first strip any existing HTML line breaks before applying nl2br().

// Example code snippet to convert line breaks to HTML line breaks
$text = &quot;Hello\nWorld&quot;;
$text = strip_tags($text); // Strip existing HTML tags
$text = nl2br($text); // Convert newline characters to HTML line breaks
echo $text;