Better parsing for the <pre> tag for Syntax Highlighter

I found out how to have a better parsing solution for using Syntax Highlighter on your system.

The Syntax Highlighter provides that you use:

  1. <pre name = "code" class = "cpp">
  2. ...some code goes here...
  3. </pre>

...to define a code syntax highlighting block. Well if you are storing this in a database you need the proper parsing to make it output to the user correctly, assuming you sanitize special characters before input that data into the database.

Here is how it works: (just a simple example):

  1. <?php
  2. //assuming you are getting your text from the database we will use $row['content']
  3. //you want to preserver tabs coming from the database...I've replaced tabs with 4 no break spaces
  4. $text = preg_replace("/\t/i", "&nbsp;&nbsp;&nbsp;&nbsp;", $row['content']);
  5.  
  6. //...any other parsing for entire content body through the $parsed_text ..then
  7.  
  8. $parsed_text = htmlspecialchars_decode(stripslashes($parsed_text));
  9.  
  10. //now we will make a function called nl2brPre() that acts just like nl2br but is more robust on handling line breaks in <pre> tags using the Syntax Highlighter
  11.  
  12. function nl2brPre($string, $is_xhtml = true) {
  13.         $str = explode("\n", $string);
  14.         $op = '';
  15.         for ($i = 0; $i < sizeof($str); $i++) {
  16.                 if (preg_match("/\<pre[^\>]/i", $str[$i])) {
  17.                         $op .= trim($str[$i])."\n";
  18.                         $n = $i+1;
  19.                         for ($j = $n; $j < sizeof($str); $j++, $i++) {
  20.                                 if (preg_match("/\<\/pre>/i", $str[$j])) {
  21.                                         $op .= trim($str[$j]);
  22.                                         break;
  23.                                 }
  24.                                 if (preg_match("/\<\?php/i", $str[$j]))
  25.                                         $str[$j] = preg_replace("/\<(\?php)/i", "&lt;$1", $str[$j]);
  26.                                 $op .= trim($str[$j])."\n";
  27.                         }
  28.                 } else {
  29.                         $op .= trim($str[$i]).(($is_xhtml == true) ? '<br />' : '<br>');
  30.                 }
  31.         }
  32.         return $op;
  33. }
  34.  
  35. //now we pass the $parsed_text to the nl2brPre() function.
  36.  
  37. print nl2brPre($parsed_text);
  38.  
  39. ?>

And there we have it. You can find an example of the full use of the code here: http://marislabs.org/ext/msdocu/reader/?f=includes/sys.php in the functions public text_parse($text) and public nl2brPre($string, $is_xhtml = true) and you can see the actual output of this here: http://marislabs.org/docu/?p=BB_Code_Use

Have fun,
Rashaud Teague