CakeFest 2025 Madrid: The Official CakePHP Conference

highlight_string

(PHP 4, PHP 5, PHP 7, PHP 8)

highlight_stringSyntax highlighting of a string

Description

highlight_string(string $string, bool $return = false): string|true

Outputs or returns html markup for a syntax highlighted version of the given PHP code using the colors defined in the built-in syntax highlighter for PHP.

Parameters

string

The PHP code to be highlighted. This should include the opening tag.

return

Set this parameter to true to make this function return the highlighted code.

Return Values

If return is set to true, returns the highlighted code as a string instead of printing it out. Otherwise, it will return true.

Changelog

Version Description
8.4.0 Return type changed from string|bool to string|true.
8.3.0 The resulting HTML has changed.

Examples

Example #1 highlight_string() example

highlight_string('');
?>

The above example will output:


<?php phpinfo(); ?>

Output of the above example in PHP 8.3:

<?php phpinfo(); ?>

Notes

Note:

When the return parameter is used, this function uses internal output buffering so it cannot be used inside an ob_start() callback function.

The HTML markup generated is subject to change.

See Also

add a note

User Contributed Notes 30 notes

up
26
stanislav dot eckert at vizson dot de
9 years ago
You can change the colors of the highlighting, like this:

ini_set("highlight.comment", "#008000");
ini_set("highlight.default", "#000000");
ini_set("highlight.html", "#808080");
ini_set("highlight.keyword", "#0000BB; font-weight: bold");
ini_set("highlight.string", "#DD0000");
?>

Like you see in the example above, you can even add additional styles like bold text, since the values are set directly to the DOM attribute "style".

Also, this function highlights only text, if it begins with the prefix "
function highlightText($text)
{
$text = trim($text);
$text = highlight_string(". $text, true); // highlight_string() requires opening PHP tag or otherwise it will not colorize the text
$text = trim($text);
$text = preg_replace("|^\\\\|", "", $text, 1); // remove prefix
$text = preg_replace("|\\
\$|"
, "", $text, 1); // remove suffix 1
$text = trim($text); // remove line breaks
$text = preg_replace("|\\\$|", "", $text, 1); // remove suffix 2
$text = trim($text); // remove line breaks
$text = preg_replace("|^(\\)(<\\?php )(.*?)(\\)|", "\$1\$3\$4", $text); // remove custom added "
return $text;
}
?>

Note, that it will remove the tag too, so you get the formatted text directly, which gives you more freedom to work with the result.

I personally suggest to combine both things to have a nice highlighting function for different file types with different highlight coloring sets:

function highlightText($text, $fileExt="")
{
if (
$fileExt == "php")
{
ini_set("highlight.comment", "#008000");
ini_set("highlight.default", "#000000");
ini_set("highlight.html", "#808080");
ini_set("highlight.keyword", "#0000BB; font-weight: bold");
ini_set("highlight.string", "#DD0000");
}
else if (
$fileExt == "html")
{
ini_set("highlight.comment", "green");
ini_set("highlight.default", "#CC0000");
ini_set("highlight.html", "#000000");
ini_set("highlight.keyword", "black; font-weight: bold");
ini_set("highlight.string", "#0000FF");
}
// ...

$text = trim($text);
$text = highlight_string(". $text, true); // highlight_string() requires opening PHP tag or otherwise it will not colorize the text
$text = trim($text);
$text = preg_replace("|^\\\\|", "", $text, 1); // remove prefix
$text = preg_replace("|\\
\$|"
, "", $text, 1); // remove suffix 1
$text = trim($text); // remove line breaks
$text = preg_replace("|\\\$|", "", $text, 1); // remove suffix 2
$text = trim($text); // remove line breaks
$text = preg_replace("|^(\\)(<\\?php )(.*?)(\\)|", "\$1\$3\$4", $text); // remove custom added "
return $text;
}
?>
up
9
www.phella.net
17 years ago
When you quote highlighted PHP code in your website you need to escape quotes. If you quote a lot it may be annoyning. Here is tiny snippet how to make quoting tidy and clean. Write your code like this:


$string = 'Here I put my code';


And somewhere else define the function:

function code()
{
static $on=false;
if (!$on) ob_start();
else
{
$buffer= "";
ob_end_clean();
highlight_string($buffer);
}
$on=!$on;
}
?>
up
2
will at lolcat dot ca
1 year ago
Here is the best way to highlight code if you want classes instead of inline styles:

function highlightcode($text){

ini_set("highlight.comment", "c-comment");
ini_set("highlight.default", "c-default");
ini_set("highlight.html", "c-default");
ini_set("highlight.keyword", "c-keyword");
ini_set("highlight.string", "c-string");

$text =
trim(
str_replace(
'
'
,
"\n", // replace
with newlines
str_replace(
[
// leading "\n<?php ",
"",
"
"
],
"",
highlight_string(". $text, true)
)
)
);

// replace colors
$classes = ["c-comment", "c-default", "c-keyword", "c-string"];

foreach(
$classes as $class){

$text = str_replace('. $class . '">', '. $class . '">', $text);
}

return
$text;
}
?>

Generates output that looks like this:

if(condition){
     echo 
"HTML here";
}


Hope this helps.
up
4
admin [at] develogix [dot] com
20 years ago
I've been working on a good replacement for the highlight_string() function; and here is what I've come up with so far:

function get_sourcecode_string($str, $return = false, $counting = true, $first_line_num = '1', $font_color = '#666'){
$str = highlight_string($str, TRUE);
$replace = array(
' ' 'color="' => 'style="color: ',
'' => '
',
'' => '',
'
' => '',
'' =>
''
);
foreach ($replace as $html => $xhtml){
$str = str_replace($html, $xhtml, $str);
}
// delete the first and the corresponding
$str = substr($str, 30, -9);

$arr_html = explode('
', $str);
$total_lines = count($arr_html);
$out = '';
$line_counter = 0;
$last_line_num = $first_line_num + $total_lines;

foreach ($arr_html as $line){
$line = str_replace(chr(13), '', $line);
$current_line = $first_line_num + $line_counter;
if ($counting){
$out .= ''
. str_repeat(' ', strlen($last_line_num) - strlen($current_line))
. $current_line
. ':
';
}
$out .= $line
. '
'."\n";
$line_counter++;
}
$out = ''."\n".$out.'."\n"';

if ($return){return $out;}
else {echo $out;}
}
?>

This function outputs valid XHTML 1.1 code by replacing font tags with span tags. You can also specify whether you want it to return or echo, output a line-count, the color of the line-count, and the starting line-count number.

Usage:
// $str = string with php
// $return = true (return) / false (echo)
// default of false
// $counting = true (count) / false (don't count)
// default of true
// $start = starting count number
// default of '1'
// $color = count color with preceding #
// defalut of '#666'
get_sourcecode_string($str, $return, $counting, $start, $color);
?>
up
1
gaggge at gmail dot com
20 years ago
This is a little function for highlighting bbcode-stylish PHP code from a mysql database.
(Like this: [php]echo "test"; ?>[/php])

function bbcode($s)
{
$s = str_replace("]\n", "]", $s);
$match = array('#\[php\](.*?)\[\/php\]#se');
$replace = array("'
'.highlight_string(stripslashes('$1'), true).'
'"
);
return
preg_replace($match, $replace, $s);
}
?>
up
1
Pyerre
18 years ago
This fonction replaces every space with the html code   (non-breaking space)
this is not very good because text will not go to the line and causes a big width
for example in a bordered div, text will go across the border

my solution :
echo str_replace(" ", " ",highlight_string("Arise, you children of the fatherland",true));
echo str_replace(" ", " ",highlight_file("test.php",true));
up
1
Dmitry S
16 years ago
Alternative XML syntax highlighting.

function xml_highlight($s)
{
$s = htmlspecialchars($s);
$s = preg_replace("#<([/]*?)(.*)([\s]*?)>#sU",
"<\\1\\2\\3>",$s);
$s = preg_replace("#<([\?])(.*)([\?])>#sU",
"<\\1\\2\\3>",$s);
$s = preg_replace("#<([^\s\?/=])(.*)([\[\s/]|>)#iU",
"<\\1\\2\\3",$s);
$s = preg_replace("#<([/])([^\s]*?)([\s\]]*?)>#iU",
"<\\1\\2\\3>",$s);
$s = preg_replace("#([^\s]*?)\=("|')(.*)("|')#isU",
"\\1=\\2\\3\\4",$s);
$s = preg_replace("#<(.*)(\[)(.*)(\])>#isU",
"<\\1\\2\\3\\4>",$s);
return
nl2br($s);
}
?>
up
1
w at w87 dot eu
2 days ago
Function highlight_string() in its pure form is IMHO rather messy.
But it can be easily made tidy and more handy with minor changes and CSS use:

● Line numbers of code (based on HTML
    &
  1. , so they don't mess selecting code)
    ● Optional loading code from a file
    ● Tidy code:
    ● Replacing style attributes with use of CSS classes
    ● Removing unnecessary tags
    ● Countless   to spaces (CSS handles that) etc.

    /**
    * Code syntax highlighting
    *
    * @version 2025.06.12
    * @author Walerian Walawski
    * @link https://w87.eu/
    *
    * @param string|null $file — path of a file to load or null to use OB
    */

    function w87HighlightCode($file = null)
    {
    static
    $w87HighlightCodeOn = false;

    ini_set('highlight.comment', 'comment');
    ini_set('highlight.default', 'default');
    ini_set('highlight.html', 'html');
    ini_set('highlight.keyword', 'keyword');
    ini_set('highlight.string', 'string');

    if(!
    $file && !$w87HighlightCodeOn){
    ob_start();
    $w87HighlightCodeOn = true;
    }else{
    $code = highlight_string(trim($file ? file_get_contents($file) : ".ob_get_contents()."\n?>"), true);
    $code = preg_replace(["|^\\\\|", "|\\\$|", "|\\\$|"], '', trim($code), 1);
    $code = str_replace([' style="color: ', '
    '
    , ' '], [' class="w87-hc-', '
  2. ', ' '], trim($code));

    if(!
    $file) ob_end_clean();
    $w87HighlightCodeOn = false;

    return
    '
    1. '.$code.'
    '
    ;
    }
    }

    /** -----------------------------------------------------------------------------
    * Use the function above with the CSS included in your styles file or in :
    * ------------------------------------------------------------------------------



    */
    ?>

    Using to highlight code in a file:

    echo w87HighlightCode(__DIR__.'/fileName.php');
    ?>

    Using with output buffering for handy embedding code:

    echo '

    This is a test code example

    '
    ;
    w87HighlightCode(); ?>
    echo "Now 'quetes' and $other \n $special chars. don't require 'escaping'!";
    echo w87HighlightCode(); ?>
up
1
manithu at fahr-zur-hoelle dot org
20 years ago
This function will return highlighted, xhtml 1.1 valid code (replaces with elements and color with style attributes):


function xhtml_highlight($str) {
$str = highlight_string($str, true);
//replace
$str = preg_replace('#([^\']*)#', '\\2', $str);
//replace other elements
return preg_replace('#([^\']*)#U', '\\2', $str);
}

?>
up
0
pyetrosafe at gmail dot com
6 years ago
I read the note from "stanislav dot eckert at vizson dot de" and I really enjoyed the function he created.
For my use I made some adaptations leaving the function more practical and allowing the passage and multiple parameters at a time, I also modified the style of the element with a black background and margins.


// Combined of the highlight_string and var_export
function hl_export()
{
try {
ini_set("highlight.comment", "#008000");
ini_set("highlight.default", "#FFFFFF");
ini_set("highlight.html", "#808080");
ini_set("highlight.keyword", "#0099FF; font-weight: bold");
ini_set("highlight.string", "#99FF99");

$vars = func_get_args();

foreach (
$vars as $var ) {
$output = var_export($var, true);
$output = trim($output);
$output = highlight_string(". $output, true); // highlight_string() requires opening PHP tag or otherwise it will not colorize the text
$output = preg_replace("|\\|", "", $output, 1); // edit prefix
$output = preg_replace("|(\\)(<\\?php )(.*?)(\\)|", "\$1\$3\$4", $output); // remove custom added " echo $output;
}
} catch (
Exception $e) {
echo
$e->getMessage();
}
}

// Debug multiple vars at once.
$var1 = 'Example String';
$var2 = 1987;
$var3 = null;
$var4 = true;
$var5 = array('Array', '05', 05, false, null);

hl_export( $var1, $var2, $var3, $var4, $var5 );
?>
up
0
stanislav dot eckert at vizson dot de
10 years ago
The documentation says for the first parameter "The PHP code to be highlighted. This should include the opening tag. ". But it seems that the code should not only but *must* start with PHP's opening tag or otherwise the function will still modify but will not highlight the code.
up
0
Mean^_^
16 years ago
[EDIT BY danbrown AT php DOT net: The following note contains a user-supplied version of a syntax highlighter.]



function printCode($code, $lines_number = 0) {

if (!
is_array($code)) $codeE = explode("\n", $code);
$count_lines = count($codeE);

$r1 = "Code:
"
;

if (
$lines_number){
$r1 .= "
";
foreach(
$codeE as $line =>$c) {
if(
$count_lines=='1')
$r1 .= "1
"
;
else
$r1 .= ($line == ($count_lines - 1)) ? "" : ($line+1)."
"
;
}
$r1 .= "
"
;
}

$r2 = "
";
$r2 .= highlight_string($code,1);
$r2 .= "
"
;

$r .= $r1.$r2;

echo
"
".$r."
\n"
;
}

printCode(' ',1);
?>

by mean
Share idea.
good luck ^_^
up
0
fsx dot nr01 at gmail dot com
17 years ago
Here is an improved version of the code highlighter w/ linenumbers from 'vanessaschissato at gmail dot com' - http://nl.php.net/manual/en/function.highlight-string.php#70456


function printCode($source_code)
{

if (
is_array($source_code))
return
false;

$source_code = explode("\n", str_replace(array("\r\n", "\r"), "\n", $source_code));
$line_count = 1;

foreach (
$source_code as $code_line)
{
$formatted_code .= ''.$line_count.'';
$line_count++;

if (
ereg('<\?(php)?[^[:graph:]]', $code_line))
$formatted_code .= ''. str_replace(array('', ''
), '', highlight_string($code_line, true)).'';
else
$formatted_code .= ''.ereg_replace('(<\?php )+', '', str_replace(array('', ''), '', highlight_string('.$code_line, true))).'';
}

return
''.$formatted_code.'
'
;
}

?>
up
0
Dobromir Velev
17 years ago
Here is an improved version of Dimitry's xml_highlight function.
I fixed a bug which replaced the first character of the tags name,
and added a line to replace the tabs and spaces with
non-breaking space symbols to keep the identation.

function xml_highlight($s){
$s = preg_replace("|<([^/?])(.*)\s(.*)>|isU", "[1]<[2]\\1\\2[/2] [5]\\3[/5]>[/1]", $s);
$s = preg_replace("||isU", "[1][/1]", $s);
$s = preg_replace("|<\?(.*)\?>|isU","[3][/3]", $s);
$s = preg_replace("|\=\"(.*)\"|isU", "[6]=[/6][4]\"\\1\"[/4]",$s);
$s = htmlspecialchars($s);
$s = str_replace("\t","  ",$s);
$s = str_replace(" "," ",$s);
$replace = array(1=>'0000FF', 2=>'0000FF', 3=>'800000', 4=>'FF00FF', 5=>'FF0000', 6=>'0000FF');
foreach($replace as $k=>$v) {
$s = preg_replace("|\[".$k."\](.*)\[/".$k."\]|isU", "\\1", $s);
}

return nl2br($s);
}
?>
up
0
Daniel
17 years ago
Well, Just a little something I wrote which highlights an HTML code...It'll be going through many changes in the next few days.... until then =) enjoy

/*************************************\
CODE PANE 1.0 - SILVERWINGS - D. Suissa
\*************************************/

class HTMLcolorizer{
private
$pointer = 0; //Cursor position.
private $content = null; //content of document.
private $colorized = null;
function
__construct($content){
$this->content = $content;
}
function
colorComment($position){
$buffer = "<";
for(
$position+=1;$position < strlen($this->content) && $this->content[$position] != ">" ;$position++){
$buffer.= $this->content[$position];
}
$buffer .= ">"
;
$this->colorized .= $buffer;
return
$position;
}
function
colorTag($position){
$buffer = "<";
$coloredTagName = false;
//As long as we're in the tag scope
for($position+=1;$position < strlen($this->content) && $this->content[$position] != ">" ;$position++){
if(
$this->content[$position] == " " && !$coloredTagName){
$coloredTagName = true;
$buffer.=""
;
}else if(
$this->content[$position] != " " && $coloredTagName){
//Expect attribute
$attribute = "";
//While we're in the tag
for(;$position < strlen($this->content) && $this->content[$position] != ">" ;$position++){
if(
$this->content[$position] != "="){
$attribute .= $this->content[$position];
}else{
$value="";
$buffer .= "".$attribute."=";
$attribute = ""; //initialize it
$inQuote = false;
$QuoteType = null;
for(
$position+=1;$position < strlen($this->content) && $this->content[$position] != ">" && $this->content[$position] != " " ;$position++){
if(
$this->content[$position] == '"' || $this->content[$position] == "'"){
$inQuote = true;
$QuoteType = $this->content[$position];
$value.=$QuoteType;
//Read Until next quotation mark.
for($position+=1;$position < strlen($this->content) && $this->content[$position] != ">" && $this->content[$position] != $QuoteType ;$position++){
$value .= $this->content[$position];
}
$value.=$QuoteType;
}else{
//No Quotation marks.
$value .= $this->content[$position];
}
}
$buffer .= "".$value."";
break;
}

}
if(
$attribute != ""){$buffer.="".$attribute."";}
}
if(
$this->content[$position] == ">" ){break;}else{$buffer.= $this->content[$position];}

}
//In case there were no attributes.
if($this->content[$position] == ">" && !$coloredTagName){
$buffer.=">"
;
$position++;
}
$this->colorized .= $buffer;
return --
$position;
}
function
colorize(){
$this->colorized="";
$inTag = false;
for(
$pointer = 0;$pointer<strlen($this->content);$pointer++){
$thisChar = $this->content[$pointer];
$nextChar = $this->content[$pointer+1];
if(
$thisChar == "<"){
if(
$nextChar == "!"){
$pointer = $this->colorComment($pointer);
}else if(
$nextChar == "?"){
//colorPHP();
}else{
$pointer = $this->colorTag($pointer);
}
}else{
$this->colorized .= $this->content[$pointer];
}
}
return
$this->colorized;
}
}
$curDocName = $_REQUEST['doc'];
$docHandle = fopen($curDocName,"r");
$docStrContent = fread($docHandle,filesize($curDocName));
fclose($docHandle);
$HTMLinspector = new HTMLcolorizer($docStrContent);
$document = $HTMLinspector->colorize();
?>






echo "
".$document."
"
;
?>

up
0
wm at tellinya dot com
17 years ago
I wanted to build a better function and exclude operators {}=- from keywords span class. I also wanted to link functions used in my PHP code directly to the PHP site.
A lot more changes and tweaks have been made and the output is much better!

Find the function here :
http://www.tellinya.com/art2/262/highligh-php-syntax/
and ditch the old PHP one permanently.
Tested and built on PHP 5.2.0.

Looking forward to any input.
up
0
stalker at ruun dot de
19 years ago
to vouksh: I expanded your functions a bit:

function xhtmlHighlightString($str,$return=false) {
$hlt = highlight_string(stripslashes($str), true);
$fon = str_replace(array(', ''), array(', ''), $hlt);
$ret = preg_replace('#color="(.*?)"#', 'style="color: \\1"', $fon);
if(
$return)
return
$ret;
echo
$ret;
return
true;
}
function
xhtmlHighlightFile($path,$return=false) {
$hlt = highlight_file($path, true);
$fon = str_replace(array(', ''), array(', ''), $hlt);
$ret = preg_replace('#color="(.*?)"#', 'style="color: \\1"', $fon);
if(
$return)
return
$ret;
echo
$ret;
return
true;
}
?>
up
0
vouksh at vouksh dot info
19 years ago
Fully working, XHTML 1.1 ready xhtml_highlight function. I included the stripslashes, because of some problems I had with out it. It should be safe to leave it in there, but if you experience problems, feel free to take it out.

function xhtml_highlight($str) {
$hlt = highlight_string(stripslashes($str), true);
$fon = str_replace(array(''), array(''), $hlt);
$ret = preg_replace('#color="(.*?)"#', 'style="color: \\1"', $fon);
echo $ret;
return true;
}
?>
up
0
zer0
19 years ago
Concerning my code below:

I'm sorry, I completely forgot about str_ireplace being for PHP 5 for some reason. Also, there was another error I missed (too many late nights ;)). Here's the corrected code:

function highlight_code($code, $inline=false, $return=false) // Pre php 4 support for capturing highlight
{
(string)
$highlight = "";
if (
version_compare(PHP_VERSION, "4.2.0", "<") === 1 )
{
ob_start(); // start output buffering to capture contents of highlight
highlight_string($code);
$highlight = ob_get_contents(); // capture output
ob_end_clean(); // clear buffer cleanly
}
else
{
$highlight=highlight_string($code, true);
}

# Using preg_replace will allow PHP 4 in on the fun
if ( $inline === true )
$highlight=preg_replace("//i","",$highlight);
else
$highlight=preg_replace("//i","",$highlight);

if (
$return === true )
{
return
$highlight;
}
else
{
echo
$highlight;
}
}
?>
up
0
Sam Wilson
19 years ago
manithu at fahr-zur-hoelle dot org forgot only one thing: to fix the break tags. The addidtion of the following should do it.

$str = str_replace("
"
, "
"
, $str);
?>
up
0
bpgordon at gmail dot com
20 years ago
On dleavitt AT ucsc DOT edu's comment:

You might want to use md5($html_string) instead of "piggusmaloy" as a generally good programming practice. Just in case "piggusmaloy" is actually in $html_string.
up
0
trixsey at animania dot nu
20 years ago
A neat function I made. Syntax coloring, row numbers, varying background colors per row in the table.

function showCode($code) {
$html = highlight_string($code, true);
$html = str_replace("\n", "", $html);
$rows = explode("
", $html);

$row_num = array();
$i = 1;

foreach($rows as $row) {
if($i < 10) {
$i = "0".$i;
}

if($i==1) {
$row_num[] = "$i\t$row";
}

if($i!=1) {
if(is_int($i/2)) {
$row_num[] = "$i\t$row";
} else {
$row_num[] = "$i\t$row";
}
}

$i++;
}
return "
\nFilename: $_GET[file]\n    style=\"border:1px #000000 solid\">".implode($row_num)."
";
}
?>
up
0
support at superhp dot de
20 years ago
With this function you can highlight php code with line numbers:

function highlight_php($string)
{
$Line = explode("\n",$string);

for(
$i=1;$i<=count($Line);$i++)
{
$line .= " ".$i.
"
;
}

ob_start();
highlight_string($string);
$Code=ob_get_contents();
ob_end_clean();

$header='







Php-Code:
'.$line.'
';

$footer=$Code.'
'
;

return
$header.$footer;
}
?>
up
0
admin at bwongar dot com
20 years ago
I didn't get the expected results from the other XHTML_highlight function, so I developed my own and it is much more efficient. The older one uses a preg_replace to replace the contents of the tag to within a span tag. The only preg_replace in my function pulls the color attribute, and puts it within a str_replace'd span tag.

function xhtml_highlight($str) {
$str = highlight_string($str, true);
$str = str_replace(array(', ''), array(', ''), $str);
return
preg_replace('#color="(.*?)"#', 'style="color: \\1"', $str);
}

?>
up
-1
peter at int8 dot com
19 years ago
This hasn't been mentioned, but it appears that PHP opening and closing tags are required to be part of the code snippet.
(""); ?>
works, while
("\$var = 15;"); ?>
does not. This is unforunate for those of use who want to show tiny code snippets, but there you go. Earlier versions of this function did not have this requirement, if I remember correctly.
up
-1
supremacy2k at gmail dot com
18 years ago
A simplification of functions vanessaschissato at gmail dot com at 17-Oct-2006 05:04.

Since it had trouble keeping the code intact. (It removed /* )

function showCode($code) {
$code = highlight_string($code, true);
$code = explode("
", $code);

$i = "1";
foreach ($code as $line => $syntax) {
echo "".$i." ".$syntax."
";
$i++;
}
}
up
-1
tyler dot reed at brokeguysinc dot com
18 years ago
This is a little chunk of code that i use to show the source of a file, i took part of the idea from a example i found on another php function page.

This code takes a php file and highlights it and places a line number next to it. Great for on the fly debugging.

// Get a file into an array
$lines = file('index.php');

// Loop through our array, show HTML source as HTML source; and line numbers too.
echo('');
foreach (
$lines as $line_num => $line) {
echo(
'');
echo(
'');
echo(
'');
echo(
'');
}

?>
up
-2
joshuaeasy4u at gmail dot com
11 years ago
function printCode($source_code)
{
if (
is_array($source_code))
return
false;
$source_code=explode("\n",str_replace(array("\r\n","\r"),"\n",$source_code));
$line_count=1;
foreach (
$source_code as $code_line)
{
$formatted_code .='
';
$line_count++;
if (
ereg('<\?(php)?[^[:graph:]]',$code_line))
$formatted_code.='
';
else
$formatted_code .='
';
}
return
'
');
echo(
'' . ($line_num + 1) . '');
echo(
'
');
highlight_string($line);
echo(
'
'.$line_count.''.str_replace(array('',''),'',highlight_string($code_line,true)).'
'.ereg_replace('(<\?php )+','',str_replace(array('',''),'',highlight_string('.$code_line,true))).'
'.$formatted_code.'
'
;
}
?>
up
-2
zero
19 years ago
In some cases, I found that it's useful to have highlight_string format ... inline as part of a paragraph, and other times, as a block for demonstrating multiple lines of code. I made this function to help out.

function highlight_code($code, $inline=false, $return=false) // Pre php 4 support for capturing highlight
{
(string)
$highlight = "";
if (
version_compare(phpversion(), "4.2.0", "<") === 1 )
{
ob_start(); // start output buffering to capture contents of highlight
highlight_string($code);
$highlight = ob_get_contents(); // capture output
ob_end_clean(); // clear buffer cleanly
}
else
{
$highlight=highlight_string($data, true);
}

## The classes below need to correspond to a stylesheet!
if ( $inline === true )
$highlight=str_ireplace("","",$highlight);
else
$highlight=str_ireplace("","",$highlight);


if (
$return === true )
{
return
$highlight;
}
else
{
echo
$highlight;
}
}
?>
up
-4
Dmitry S
17 years ago
The simple XML syntax highlighting.

function xml_highlight($s)
{
$s = preg_replace("|<[^/?](.*)\s(.*)>|isU","[1]<[2]\\1[/2] [5]\\2[/5]>[/1]",$s);
$s = preg_replace("||isU","[1][/1]",$s);
$s = preg_replace("|<\?(.*)\?>|isU","[3][/3]",$s);
$s = preg_replace("|\=\"(.*)\"|isU","[6]=[/6][4]\"\\1\"[/4]",$s);
$s = htmlspecialchars($s);
$replace = array(1=>'0000FF', 2=>'808000', 3=>'800000', 4=>'FF00FF', 5=>'FF0000', 6=>'0000FF');
foreach(
$replace as $k=>$v)
{
$s = preg_replace("|\[".$k."\](.*)\[/".$k."\]|isU",".$v."\">\\1",$s);
}
return
nl2br($s);
}
?>
To Top