Zend - The PHP Company




Source Viewers

Add Code


Syntax Highlighted Code with Line Numbers  

Type: application
Added by: spellofweb
Entered: 03/12/2003
Last modified: 02/11/2002
Rating: - (fewer than 3 votes)
Views: 5271
Let me read your mind: - You want to add line numbers to highlighted source code. - You hate Output Buffering; you love speed. - You want to serve a valid XHTML code. - You want a function to return the highlighted code, instead of printing it out. Let me present my solution:


<?php

function get_sourcecode($filename$first_line_num=1$num_color="#999") {


    
// Get highlighted code
    
$html_code highlight_file($filenameTRUE);


    
// Bookmark #1:
    // Remove the first "<code>" tag from "$html_code" (if any)
    
if (substr($html_code06) == "<code>") {
        
$html_code substr($html_code6strlen($html_code));
    }


    
// Replacement-map to replace deprecated "<font>" tag with "<span>"
    
$xhtml_convmap = array(
        
'<font' => '<span',
        
'</font>' => '</span>',
        
'color="' => 'style="color:'
    
);

    
// Replace "<font>" tags with "<span>" tags, to generate a valid XHTML code
    
$html_code strtr($html_code$xhtml_convmap);


    
### Okay, Now we have a valid XHTML code
    ### Let's add the line numbers...


    
$arr_html_code explode("<br />"$html_code);
    
$total_lines count($arr_html_code);


    
$retval "";
    
$line_counter 0;
    
$last_line_num $first_line_num $total_lines;
    foreach (
$arr_html_code as $html_line) {

        
// Calculate number of current line
        
$current_line $first_line_num $line_counter;

        
// Append new line to "$retval"
        
$retval .=
            
str_repeat("&nbsp;"strlen($last_line_num) - strlen($current_line) ) .
            
"<span style="color:{$num_color}">{$current_line}: </span>" .
            
$html_line .
            
"<br />"
        
;

        
$line_counter++;

    } 
// end: foreach

        
    
$retval "<code>" $retval;    // Why? remember Bookmark #1, that I removed the tag "<code>"

    
return $retval;


// end: get_sourcecode

?>


Usage Example


<?php

// Print source code of "index.php" by default options
echo get_sourcecode("index.php");

// Print source code of "index.php", set the first-line's number to 0.
echo get_sourcecode("index.php"0);

// Print source code of "index.php", set the first-line's number to 0, and use color "#9966FF" to highlight line numbers
echo get_sourcecode("index.php"0"#96F");

?>


Rate This Script





Search



This Category All Categories