note 89320 deleted from function.nl2br by googleguy

From: Date: Thu, 13 Jun 2013 11:11:02 +0000
Subject: note 89320 deleted from function.nl2br by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-195182@lists.php.net to get a copy of this message
Note Submitter: sean at boyercentral dot net ---- 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!

« previous php.notes (#195182) next »