How can one ensure XHTML validity when converting line breaks in PHP?

When converting line breaks in PHP, it is important to ensure that the resulting XHTML is valid by using the correct tags for line breaks. Instead of using the traditional <br> tag, it is recommended to use <br /> for XHTML compatibility. This will help in maintaining the validity of the XHTML code.

// Convert line breaks to XHTML valid format
$text = &quot;This is a text with line breaks.\nLine break 1.\nLine break 2.&quot;;
$xhtml_text = nl2br($text);
echo str_replace(&quot;&lt;br&gt;&quot;, &quot;&lt;br /&gt;&quot;, $xhtml_text);