note 76507 added to function.nl2br

From: Date: Wed, 18 Jul 2007 17:07:51 +0000
Subject: note 76507 added to function.nl2br
Groups: php.notes 
Request: Send a blank email to php-notes+get-128694@lists.php.net to get a copy of this message
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); } ?> ---- Server IP: 208.69.120.35 Probable Submitter: 208.247.75.49 ---- Manual Page -- http://www.php.net/manual/en/function.nl2br.php Edit -- https://master.php.net/note/edit/76507 Del: integrated -- https://master.php.net/note/delete/76507/integrated Del: useless -- https://master.php.net/note/delete/76507/useless Del: bad code -- https://master.php.net/note/delete/76507/bad+code Del: spam -- https://master.php.net/note/delete/76507/spam Del: non-english -- https://master.php.net/note/delete/76507/non-english Del: in docs -- https://master.php.net/note/delete/76507/in+docs Del: other reasons-- https://master.php.net/note/delete/76507 Reject -- https://master.php.net/note/reject/76507 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#128694) next »