note 89320 added to function.nl2br

From: Date: Tue, 03 Mar 2009 15:22:39 +0000
Subject: note 89320 added to function.nl2br
Groups: php.notes 
Request: Send a blank email to php-notes+get-151397@lists.php.net to get a copy of this message
Ever had a problem with using nl2br() for something like a blog post which contains anything inside of a <pre> tag? It will give you double spaces. Ugly for posting code examples. Here's my solution. If it doesn't detect a <pre> tag inside of the $string you pass in, it uses regular ol' nl2br(). Otherwise, it explodes the string by \n, and only adds <br /> to lines that are NOT inside the <pre> tag! This function completely avoids using RegEx and stacks. Simple, and fairly fast. <?php // do nl2br except when in a pre tag function nl2brPre($string) { // First, check for <pre> tag if(!strpos($string, "<pre>")) { return nl2br($string); } // If there is a <pre>, we have to split by line // and manually replace the linebreaks with <br /> $strArr=explode("\n", $string); $output=""; $preFound=false; // Loop over each line foreach($strArr as $line) { // See if the line has a <pre>. If it does, set $preFound to true if(strpos($line, "<pre>")) { $preFound=true; } elseif(strpos($line, "</pre>")) { $preFound=false; } // If we are in a pre tag, just give a \n, else a <br /> if($preFound) { $output .= $line . "\n"; } else { $output .= $line . "<br />"; } } return $output; } ?> Hope this comes in handy! ---- Server IP: 216.235.13.26 Probable Submitter: 142.166.3.42 ---- Manual Page -- http://www.php.net/manual/en/function.nl2br.php Edit -- https://master.php.net/note/edit/89320 Del: integrated -- https://master.php.net/note/delete/89320/integrated Del: useless -- https://master.php.net/note/delete/89320/useless Del: bad code -- https://master.php.net/note/delete/89320/bad+code Del: spam -- https://master.php.net/note/delete/89320/spam Del: non-english -- https://master.php.net/note/delete/89320/non-english Del: in docs -- https://master.php.net/note/delete/89320/in+docs Del: other reasons-- https://master.php.net/note/delete/89320 Reject -- https://master.php.net/note/reject/89320 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#151397) next »