note 76507 deleted from function.nl2br by nlopess
| From: | nlopess@php.net | Date: | Wed, 18 Jul 2007 17:13:42 +0000 |
| Subject: | note 76507 deleted from function.nl2br by nlopess | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-128695@lists.php.net to get a copy of this message | ||
Note Submitter: lucky760 located at yahoo period com
----
This simple, yet somewhat elegant solution I'm using on http://www.VideoSift.com handles converting newlines to <br
/> taking into consideration that HTML tags might be broken across multiple lines. With nl2br() a
string like "This is a <a\nhref="#">link</a>" would become
"This is a <a<br />href="#">link</a>".
My version detects whether a newline is within an HTML tag by simply checking if the last opening
angle bracket ("<") on the line is greater than the last closing angle bracket
(">") or if no such closer exists. If so, we know for certain the newline is embedded
within a tag and the <br /> tag is not appended.
(There may be other versions of such a function somewhere else on this rather lengthy page, but this
is my take on it.)
<?php
public static function html_nl2br($i_str) {
// split into an array by line (being overly careful about newline chars)
$i_str = str_replace("\r\n", "\n", $i_str);
$i_str = str_replace("\r", "\n", $i_str);
$lines = split("\n", $i_str);
// append a <br> to each line unless the line is embedded in a tag
foreach ($lines as $index => $line) {
if (!(strrpos($line, '<') > strrpos($line, '>')))
$lines[$index] .= '<br />';
}
// join the lines, insuring a space is kept between unprocessed lines
return implode(' ', $lines);
}
?>