highlight_string
(PHP 4, PHP 5, PHP 7, PHP 8)
highlight_string — 文字列の構文ハイライト表示
説明
PHP 組込みの
構文ハイライタで定義されたカラーを使用して str
を構文ハイライト表示したものを、html マークアップで出力あるいは返します。
例
例1 highlight_string() の例
<?php
highlight_string('<?php phpinfo(); ?>');
?>
上の例の出力は以下となります。
<code><span style="color: #000000"> <span style="color: #0000BB"><?php phpinfo</span><span style="color: #007700">(); </span><span style="color: #0000BB">?></span> </span> </code>
上の例の PHP 8.3 での出力は、このようになります。:
<pre><code style="color: #000000"><span style="color: #0000BB"><?php phpinfo</span><span style="color: #007700">(); </span><span style="color: #0000BB">?></span></code></pre>
注意
注意:
return
パラメータを使う場合、この関数は内部的に出力バッファリングを使います。 そのため、ob_start() コールバック関数の中では使えません。
生成される HTML マークアップは、変わる可能性があります。
+add a note
User Contributed Notes 29 notes
stanislav dot eckert at vizson dot de ¶
8 years ago
You can change the colors of the highlighting, like this:
<?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");
?>
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 "<?php". But this function can highlight other similar formats too (not perfectly, but better than nothing), like HTML, XML, C++, JavaScript, etc. I use following function to highlight different file types and it works quite good:
<?php
function highlightText($text)
{
$text = trim($text);
$text = highlight_string("<?php " . $text, true); // highlight_string() requires opening PHP tag or otherwise it will not colorize the text
$text = trim($text);
$text = preg_replace("|^\\<code\\>\\<span style\\=\"color\\: #[a-fA-F0-9]{0,6}\"\\>|", "", $text, 1); // remove prefix
$text = preg_replace("|\\</code\\>\$|", "", $text, 1); // remove suffix 1
$text = trim($text); // remove line breaks
$text = preg_replace("|\\</span\\>\$|", "", $text, 1); // remove suffix 2
$text = trim($text); // remove line breaks
$text = preg_replace("|^(\\<span style\\=\"color\\: #[a-fA-F0-9]{0,6}\"\\>)(<\\?php )(.*?)(\\</span\\>)|", "\$1\$3\$4", $text); // remove custom added "<?php "
return $text;
}
?>
Note, that it will remove the <code> 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:
<?php
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("<?php " . $text, true); // highlight_string() requires opening PHP tag or otherwise it will not colorize the text
$text = trim($text);
$text = preg_replace("|^\\<code\\>\\<span style\\=\"color\\: #[a-fA-F0-9]{0,6}\"\\>|", "", $text, 1); // remove prefix
$text = preg_replace("|\\</code\\>\$|", "", $text, 1); // remove suffix 1
$text = trim($text); // remove line breaks
$text = preg_replace("|\\</span\\>\$|", "", $text, 1); // remove suffix 2
$text = trim($text); // remove line breaks
$text = preg_replace("|^(\\<span style\\=\"color\\: #[a-fA-F0-9]{0,6}\"\\>)(<\\?php )(.*?)(\\</span\\>)|", "\$1\$3\$4", $text); // remove custom added "<?php "
return $text;
}
?>
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:
<?code()?>
$string = 'Here I put my code';
<?code()?>
And somewhere else define the function:
<?
function code()
{
static $on=false;
if (!$on) ob_start();
else
{
$buffer= "<?\n".ob_get_contents()."?>";
ob_end_clean();
highlight_string($buffer);
}
$on=!$on;
}
?>
will at lolcat dot ca ¶
1 year ago
Here is the best way to highlight code if you want classes instead of inline styles:
<?php
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(
'<br />',
"\n", // replace <br> with newlines
str_replace(
[
// leading <?php garbage
"<span style=\"color: c-default\">\n<?php ",
"<code>",
"</code>"
],
"",
highlight_string("<?php " . $text, true)
)
)
);
// replace colors
$classes = ["c-comment", "c-default", "c-keyword", "c-string"];
foreach($classes as $class){
$text = str_replace('<span style="color: ' . $class . '">', '<span class="' . $class . '">', $text);
}
return $text;
}
?>
Generates output that looks like this:
<span class="c-keyword">if(</span>condition<span class="c-keyword">){
echo </span><span class="c-string">"HTML here"</span><span class="c-keyword">;
}</span>
Hope this helps.
admin [at] develogix [dot] com ¶
19 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(
'<font' => '<span',
'color="' => 'style="color: ',
'</font>' => '</span>',
'<code>' => '',
'</code>' => '',
'<span style="color: #FF8000">' =>
'<span style="color: '.$font_color.'">'
);
foreach ($replace as $html => $xhtml){
$str = str_replace($html, $xhtml, $str);
}
// delete the first <span style="color:#000000;"> and the corresponding </span>
$str = substr($str, 30, -9);
$arr_html = explode('<br />', $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 .= '<span style="color:'.$font_color.'">'
. str_repeat(' ', strlen($last_line_num) - strlen($current_line))
. $current_line
. ': </span>';
}
$out .= $line
. '<br />'."\n";
$line_counter++;
}
$out = '<code>'."\n".$out.'</code>."\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);
?>
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('<font ', '</font>'), array('<span ', '</span>'), $hlt);
$ret = preg_replace('#color="(.*?)"#', 'style="color: \\1"', $fon);
echo $ret;
return true;
}
?>
pyetrosafe at gmail dot com ¶
5 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 <code> element with a black background and margins.
<?php
// 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("<?php " . $output, true); // highlight_string() requires opening PHP tag or otherwise it will not colorize the text
$output = preg_replace("|\\<code\\>|", "<code style='background-color: #000000; padding: 10px; margin: 10px; display: block; font: 12px Consolas;'>", $output, 1); // edit prefix
$output = preg_replace("|(\\<span style\\=\"color\\: #[a-fA-F0-9]{0,6}\"\\>)(<\\?php )(.*?)(\\</span\\>)|", "\$1\$3\$4", $output); // remove custom added "<?php "
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 );
?>
Dmitry S ¶
16 years ago
Alternative XML syntax highlighting.
<?php
function xml_highlight($s)
{
$s = htmlspecialchars($s);
$s = preg_replace("#<([/]*?)(.*)([\s]*?)>#sU",
"<font color=\"#0000FF\"><\\1\\2\\3></font>",$s);
$s = preg_replace("#<([\?])(.*)([\?])>#sU",
"<font color=\"#800000\"><\\1\\2\\3></font>",$s);
$s = preg_replace("#<([^\s\?/=])(.*)([\[\s/]|>)#iU",
"<<font color=\"#808000\">\\1\\2</font>\\3",$s);
$s = preg_replace("#<([/])([^\s]*?)([\s\]]*?)>#iU",
"<\\1<font color=\"#808000\">\\2</font>\\3>",$s);
$s = preg_replace("#([^\s]*?)\=("|')(.*)("|')#isU",
"<font color=\"#800080\">\\1</font>=<font color=\"#FF00FF\">\\2\\3\\4</font>",$s);
$s = preg_replace("#<(.*)(\[)(.*)(\])>#isU",
"<\\1<font color=\"#800080\">\\2\\3\\4</font>>",$s);
return nl2br($s);
}
?>
manithu at fahr-zur-hoelle dot org ¶
20 years ago
This function will return highlighted, xhtml 1.1 valid code (replaces <font> with <span> elements and color with style attributes):
<?php
function xhtml_highlight($str) {
$str = highlight_string($str, true);
//replace <code><font color=""></font></code>
$str = preg_replace('#<font color="([^\']*)">([^\']*)</font>#', '<span style="color: \\1">\\2</span>', $str);
//replace other <font> elements
return preg_replace('#<font color="([^\']*)">([^\']*)</font>#U', '<span style="color: \\1">\\2</span>', $str);
}
?>
gaggge at gmail dot com ¶
19 years ago
This is a little function for highlighting bbcode-stylish PHP code from a mysql database.
(Like this: [php]<?php echo "test"; ?>[/php])
<?php
function bbcode($s)
{
$s = str_replace("]\n", "]", $s);
$match = array('#\[php\](.*?)\[\/php\]#se');
$replace = array("'<div>'.highlight_string(stripslashes('$1'), true).'</div>'");
return preg_replace($match, $replace, $s);
}
?>
Pyerre ¶
17 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));
stalker at ruun dot de ¶
18 years ago
to vouksh: I expanded your functions a bit:
<?php
function xhtmlHighlightString($str,$return=false) {
$hlt = highlight_string(stripslashes($str), true);
$fon = str_replace(array('<font ', '</font>'), array('<span ', '</span>'), $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('<font ', '</font>'), array('<span ', '</span>'), $hlt);
$ret = preg_replace('#color="(.*?)"#', 'style="color: \\1"', $fon);
if($return)
return $ret;
echo $ret;
return true;
}
?>
Dobromir Velev ¶
16 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]</[2]\\1[/2]>[/1]", $s);
$s = preg_replace("|<\?(.*)\?>|isU","[3]<?\\1?>[/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", "<font color=\"#".$v."\">\\1</font>", $s);
}
return nl2br($s);
}
?>
stanislav dot eckert at vizson dot de ¶
9 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.
Mean^_^ ¶
15 years ago
[EDIT BY danbrown AT php DOT net: The following note contains a user-supplied version of a syntax highlighter.]
<style type="text/css">
.linenum{
text-align:right;
background:#FDECE1;
border:1px solid #cc6666;
padding:0px 1px 0px 1px;
font-family:Courier New, Courier;
float:left;
width:17px;
margin:3px 0px 30px 0px;
}
code {/* safari/konq hack */
font-family:Courier New, Courier;
}
.linetext{
width:700px;
text-align:left;
background:white;
border:1px solid #cc6666;
border-left:0px;
padding:0px 1px 0px 8px;
font-family:Courier New, Courier;
float:left;
margin:3px 0px 30px 0px;
}
br.clear {
clear:both;
}
</style>
<?php
function printCode($code, $lines_number = 0) {
if (!is_array($code)) $codeE = explode("\n", $code);
$count_lines = count($codeE);
$r1 = "Code:<br />";
if ($lines_number){
$r1 .= "<div class=\"linenum\">";
foreach($codeE as $line =>$c) {
if($count_lines=='1')
$r1 .= "1<br>";
else
$r1 .= ($line == ($count_lines - 1)) ? "" : ($line+1)."<br />";
}
$r1 .= "</div>";
}
$r2 = "<div class=\"linetext\">";
$r2 .= highlight_string($code,1);
$r2 .= "</div>";
$r .= $r1.$r2;
echo "<div class=\"code\">".$r."</div>\n";
}
printCode('<?php echo "PHP Code" ?> ',1);
?>
by mean
Share idea.
good luck ^_^
fsx dot nr01 at gmail dot com ¶
16 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
<?php
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 .= '<tr><td>'.$line_count.'</td>';
$line_count++;
if (ereg('<\?(php)?[^[:graph:]]', $code_line))
$formatted_code .= '<td>'. str_replace(array('<code>', '</code>'), '', highlight_string($code_line, true)).'</td></tr>';
else
$formatted_code .= '<td>'.ereg_replace('(<\?php )+', '', str_replace(array('<code>', '</code>'), '', highlight_string('<?php '.$code_line, true))).'</td></tr>';
}
return '<table style="font: 1em Consolas, \'andale mono\', \'monotype.com\', \'lucida console\', monospace;">'.$formatted_code.'</table>';
}
?>
Daniel ¶
16 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
<?php
/*************************************\
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 = "<<span class='HTMLComment'>";
for($position+=1;$position < strlen($this->content) && $this->content[$position] != ">" ;$position++){
$buffer.= $this->content[$position];
}
$buffer .= "</span>>";
$this->colorized .= $buffer;
return $position;
}
function colorTag($position){
$buffer = "<<span class='tagName'>";
$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.="</span>";
}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 .= "<span class='tagAttribute'>".$attribute."</span>=";
$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 .= "<span class='tagValue'>".$value."</span>";
break;
}
}
if($attribute != ""){$buffer.="<span class='tagAttribute'>".$attribute."</span>";}
}
if($this->content[$position] == ">" ){break;}else{$buffer.= $this->content[$position];}
}
//In case there were no attributes.
if($this->content[$position] == ">" && !$coloredTagName){
$buffer.="</span>>";
$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();
?>
<html>
<head>
<style type="text/css">
/**********************\
* MOZILLA FIREFOX STYLE
\**********************/
/*pre{font-family:Tahoma;font-size:px;}*/
.tagName{color:purple;}
.tagAttribute{color:red;}
.tagValue{color:blue;}
.HTMLComment{font-style:italic;color:green;}
</style>
</head>
<body>
<?php
echo "<pre>".$document."</pre>";
?>
</body>
</html>