note 97692 added to function.nl2br

From: Date: Mon, 03 May 2010 16:02:14 +0000
Subject: note 97692 added to function.nl2br
Groups: php.notes 
Request: Send a blank email to php-notes+get-168886@lists.php.net to get a copy of this message
SORRY there was an error in my previous note (in nl2br_revert_noregex, "$string =" should be "return"). I fixed it and reformated the code a little bit, for more readability. I would be thankful someone could replace my previous post by this one (without this "header" of course) :s --- *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 ); } ?> ---- Server IP: 89.31.146.176 Probable Submitter: 82.230.64.189 ---- Manual Page -- http://www.php.net/manual/en/function.nl2br.php Edit -- https://master.php.net/note/edit/97692 Del: integrated -- https://master.php.net/note/delete/97692/integrated Del: useless -- https://master.php.net/note/delete/97692/useless Del: bad code -- https://master.php.net/note/delete/97692/bad+code Del: spam -- https://master.php.net/note/delete/97692/spam Del: non-english -- https://master.php.net/note/delete/97692/non-english Del: in docs -- https://master.php.net/note/delete/97692/in+docs Del: other reasons-- https://master.php.net/note/delete/97692 Reject -- https://master.php.net/note/reject/97692 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#168886) next »