Is it just み?

WordPress: Highlight PHP Code

by on Nov.22, 2009, under PHP, Programmierung, Technik

Ich werde mal versuchen einige meiner Einträge auf Englisch zu verfassen – um in der Übung zu bleiben.

I like to write about programming, and since I am using WordPress and writing plugins for it, PHP is the language of choice when it comes to blog-related development.

I wanted to put my PHP-Code into my entries and I wanted it to look nice, which means mono-spaced font and syntax highlighting. The first one was fairly easy to archieve by just changing the CSS. Whenever I put code into my blog, I write it between <pre> and </pre>, so I just had to change the CSS for the pre-element:

 pre {
    height: auto; 
    overflow: auto;
    color: #EEE;
    padding: 5px;
    margin: 10px;
    scroll: auto;
    font-family: Courier New, monospace;
    font-weight: bold;
    white-space: pre;
    font-size: 9pt;
    line-height: 10pt;
}

The highlighting however must be done on the server side by PHP, so I had to write another (in fact two) filter-function:


<?php


function highlightCode($content) {
    if (
false === strpos($content'<pre>')) {
        return 
$content;
    }

    
$content preg_replace_callback(
        
'|\<pre\>(.*?)\</pre\>|is',
        
'highlightCodeCallback',
        
$content
    
);

    return 
$content;
}

function 
highlightCodeCallback($matches) {
    if (
false === strpos($matches[0], '<?php')) {
        return 
$matches[0];
    }
    
    
$code $matches[0];
    
$code preg_replace(
        
'|\<code\>\s*\</code\>|is'
        
'/*§§BR§§*/'$code
    
);
    
$code strip_tags($code);
    
// Wordpress adds the space when saving
    
$code str_replace('<?php''<?php'$code); 
    
$code highlight_string($codetrue);
    
$code str_replace('/*§§BR§§*/'"\n\n"$code);
    
$code htmlspecialchars_decode($code);
    
$code str_replace('<?php''<?php'$code);

    return 
'<pre>'$code .'</pre>';
}

Ähnliche Beiträge

:, ,

Comments are closed.