note 90210 deleted from function.nl2br by googleguy

From: Date: Thu, 13 Jun 2013 11:10:50 +0000
Subject: note 90210 deleted from function.nl2br by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-195181@lists.php.net to get a copy of this message
Note Submitter: eric dot NOSPAM dot dillenseger at gmail dot com ---- An addition to sean' function: Please read http://www.php.net/manual/en/function.strpos.php and the warning about return values of strpos(). <?php // (... snip ...) if(!strpos($string, "<pre>")) // triggered if <pre> is at the beginning of the string // (... snip ...) if(strpos($line, "<pre>")) // this time, not triggered if <pre> is at the beginning of the line // (... snip ...) ?> Avoid shortcuts and compare boolean results strictly with '==='. BTW, <pre> elements aren't allowed inside <p> elements (xhtml strict) so one would avoid putting a <br /> element at the end of a <pre> element. <?php // do nl2br except when in a pre tag function nl2brPre($string) { // First, check for <pre> tag if(strpos($string, "<pre>") === false) { 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=3; // 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>") === true) { $preFound=1; } elseif(strpos($line, "</pre>")) { $preFound=2; } // If we are in a pre tag, just give a \n, else a <br /> switch($preFound) { case 1: // found a <pre> tag, close the <p> element $output .= "</p>\n" . $line . "\n"; break; case 2: // found the closing </pre> tag, append a newline and open a new <p> element $output .= $line . "\n<p>"; $preFound = 3; // switch to normal behaviour break; case 3: // simply append a <br /> element $output .= $line . "<br />"; break; } } return $output; } ?>

« previous php.notes (#195181) next »