note 97688 added to function.nl2br
| From: | gx at osu1 dot php dot net | Date: | Mon, 03 May 2010 11:52:45 +0000 |
| Subject: | note 97688 added to function.nl2br | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-168881@lists.php.net to get a copy of this message | ||
*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)
$string = 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/97688
Del: integrated -- https://master.php.net/note/delete/97688/integrated
Del: useless -- https://master.php.net/note/delete/97688/useless
Del: bad code -- https://master.php.net/note/delete/97688/bad+code
Del: spam -- https://master.php.net/note/delete/97688/spam
Del: non-english -- https://master.php.net/note/delete/97688/non-english
Del: in docs -- https://master.php.net/note/delete/97688/in+docs
Del: other reasons-- https://master.php.net/note/delete/97688
Reject -- https://master.php.net/note/reject/97688
Search -- https://master.php.net/manage/user-notes.php