note 97692 deleted from function.nl2br by googleguy

From: Date: Thu, 13 Jun 2013 11:10:38 +0000
Subject: note 97692 deleted from function.nl2br by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-195179@lists.php.net to get a copy of this message
Note Submitter: gx ---- *Strictly* reverts PHP's nl2br() effects (whether it was used in XHTML mode or not): <?php function nl2br_revert($string) { return preg_replace('<br(?: /)?>([\\n\\r])', '$1', $string); } ?> Indeed, in a string which was just nl2br'd: - a BR added by PHP is directly followed by a \n or a \r character, and vice versa - a PHP-added BR is either "<br />" or "<br>" (no need to match "<br/>", "<br />", "<BR>"...) Thus this function only removes PHP-added BRs (which "strictly reverts" meant). The following would be even more logical, as nl2br() doesn't use both BR forms at once: <?php function nl2br_revert_bis($string) { $br = preg_match('<br>[\\n\\r]',$string) ? '<br>' : '<br />'; return preg_replace(''.$br.'([\\n\\r])', '$1', $string); } ?> If you don't want to use regular expressions, here are "plain" alternatives: <?php function nl2br_revert_noregex($string) { // watch for order in arrays // (the first 2 elements are for the case nl2br() was used in old HTML mode) return str_replace( array("<br>\n", "<br>\r", "<br />\n", "<br />\r"), array("<br />\n", "<br />\r", "\n", "\r"), $string ); } function nl2br_revert_bis_noregex($string) { $br = (strpos($string,"<br>\n")!==false || strpos($string,"<br>\r")!==false) ? '<br>' : '<br />'; return str_replace( array($br."\n", $br."\r"), array( "\n", "\r"), $string ); } ?>

« previous php.notes (#195179) next »