note 39615 deleted from function.nl2br by irchtml
| From: | irchtml@php.net | Date: | Sat, 26 Jun 2004 17:46:11 +0000 |
| Subject: | note 39615 deleted from function.nl2br by irchtml | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-71800@lists.php.net to get a copy of this message | ||
Note Submitter: greywyvern - greywyvern - com
----
In posting some script formatted data to the screen, I noticed that if you nl2br a string containing
<pre> tags, the lines within would be double-spaced; once for the \n which is preserved by
<pre> and once for the <br />.
So I needed a way to preform a nl2br on an entire message, but exclude or revert <pre> to just
normal \n line-endings. This way, the text within <pre> tags would remain single spaced.
string nl2br_pre(string input [, int wrap])
Here's the function I made to do that. It also wraps <pre> lines to $wrap characters
wide, which you can adjust.
<?php
function nl2br_pre($string, $wrap = 40) {
$string = nl2br($string);
preg_match_all("/<pre[^>]*?>(.|\n)*?<\/pre>/", $string, $pre1);
for ($x = 0; $x < count($pre1[0]); $x++) {
$pre2[$x] = preg_replace("/<br[^>]*?>/", "", $pre1[0][$x]);
$pre2[$x] = preg_replace("/([^\n]{".$wrap."})(?!<\/pre>)/",
"$1\n", $pre2[$x]);
$pre1[0][$x] = "/".preg_quote($pre1[0][$x], "/")."/";
}
return preg_replace($pre1[0], $pre2, $string);
}
?>