Datum: 12.09.2008
	      	
	      		  	, Kategorie:
						
PHP			
		        
       
      Die PHP-Funktion nl2br() wandelt bekanntermaßen alle Zeilenumbrüche in <br /> um. Allerdings wird dabei nicht berücksichtigt, dass doppelte Zeilenumbrüche auch als Absatz formatiert werden können. Also mit <p> statt zweier <br />. Die folgende Funktion löst das Problem.
<?php  
function nl2p($text) 
{
    $text = '<p>' . $text . '</p>'; 
    $text = str_replace("\r\n\r\n", "</p><p>", $text); 
    $text = str_replace("\n\n", "</p><p>", $text); 
    $text = str_replace("\r\n", "<br />", $text); 
    $text = str_replace("\n", "<br />", $text);      
    return $text;
} 
$text = "Test 123 
Hallo Welt 
Test 8910"; 
echo nl2p($text);
?> 
 
Der HTML-Quellcode sieht damit wie folgt aus:
<p>Test 123<br />Hallo Welt</p><p>Test 8910</p>