Tipps & Tricks

PHP-Code Highlighting

PHP Code Highlighting

Mit folgender Funktion kann man aus einem Text, den PHP Code Hervorheben.
Dabei wird sämtlicher Text zwichen <div id="code"> und </div> berücksichtigt.

Beispielcode:
<?PHP
    
// Die Funktion
    
function highlight_code($text
    
 
    
 preg_match_all ('/<div id="code">(.*?)<\/div>/s'$text$ergebnis); 
    
 for($i=0;$i<count($ergebnis[1]);$i++) { 
    
  $code trim($ergebnis[1][$i]); 
    
  $code html_entity_decode($code);
    
  $code highlight_string($code,true);
    
  $code "<div id=\"code\">".$code."</div>";
    
  $text str_replace($ergebnis[0][$i],$code,$text); 
    
  
    
 return $text
    
 }
  
// Ausgabe
  
$text="Ein Beispiel-Code:\n";
  
$text.="<div id=\"code\">\n";
  
$text.="<?PHP \n";
  
$text.="echo\"test\"; \n";
  
$text.="?>\n";
  
$text.="</div>\n";
  
$text.="Das wars :)";  
  echo 
highlight_code($text);
?>

Die Ausgabe des Beispielcodes:
Ein Beispiel-Code:
<?PHP 
  echo
"test"; 
?>
Das wars :)

Viel Spass.




Zurück zur den Tricks