©
This document uses PHP Chinese website manual Release
(PHP 4, PHP 5)
highlight_string — 字符串的语法高亮
$str
[, bool $return
= false
] )使用PHP内置的语法高亮器所定义的颜色,打印输出或者返回输出或者返回语法高亮版本的PHP代码。
str
需要高亮的PHP代码,应当包含开始标签。
return
设置该参数为 TRUE
使函数返回高亮后的代码。
如果 return
设置为 TRUE
,高亮后的代码不会被打印输出,而是以字符串的形式返回。
高亮成功返回 TRUE
,否则返回 FALSE
。
版本 | 说明 |
---|---|
4.2.0 |
添加了 return 的参数。
|
Example #1 highlight_string() 例子
<?php
highlight_string ( '<?php phpinfo(); ?>' );
?>
PHP4中,上例会输出:
<code><font color="#000000"> <font color="#0000BB"><?php phpinfo</font><font color="#007700">(); </font><font color="#0000BB">?></font> </font> </code>
PHP5中,上例会输出:
<code><span style="color: #000000"> <span style="color: #0000BB"><?php phpinfo</span><span style="color: #007700">(); </span><span style="color: #0000BB">?></span> </span> </code>
Note:
当使用了
return
参数时,本函数使用其内部输出缓冲,因此不能在 ob_start() 回调函数的内部使用。
[#1] stanislav dot eckert at vizson dot de [2015-05-11 15:18:09]
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.
[#2] joshuaeasy4u at gmail dot com [2013-09-17 21:19:35]
<?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>';
}
?>
[#3] Mean^_^ [2009-04-18 21:45:52]
[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 {
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
',1);
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" ?>
?>
by mean
Share idea.
good luck ^_^
[#4] Dmitry S [2008-07-24 01:38:46]
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);
}
?>
[#5] fsx dot nr01 at gmail dot com [2008-06-13 09:22:01]
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>';
}
?>
[#6] Dobromir Velev [2008-05-27 04:04:58]
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.
<?php
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]<?php\\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);
}
?>
[#7] Dmitry S [2008-05-12 06:29:20]
The simple XML syntax highlighting.
<?php
function xml_highlight($s)
{
$s = preg_replace("|<[^/?](.*)\s(.*)>|isU","[1]<[2]\\1[/2] [5]\\2[/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);
$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","<font color=\"".$v."\">\\1</font>",$s);
}
return nl2br($s);
}
?>
[#8] Daniel [2008-02-20 02:49:01]
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
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">
.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>
[#9] wm at tellinya dot com [2007-12-17 04:32:19]
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.
[#10] www.phella.net [2007-09-05 20:47:55]
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:
<?phpcode()?>
$string = 'Here I put my code';
<?phpcode()?>
And somewhere else define the function:
<?php
";
function code()
{
static $on=false;
if (!$on) ob_start();
else
{
$buffer= "<?php\n".ob_get_contents()."?>
ob_end_clean();
highlight_string($buffer);
}
$on=!$on;
}
?>
[#11] supremacy2k at gmail dot com [2007-03-31 16:06:08]
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 FToN( $val )
{
$a = unpack("I",pack( "f",$val ));
return pack("N",$a[1] );
}
function NToF($val )
{
$a = unpack("N",$val);
$b = unpack("f",pack( "I",$a[1]));
return $b[1];
}
[#16] Patrik Fimml [2005-10-11 10:42:30]
You will get the same effect with
<?php
function _readInt($fp)
{
return unpack('V', fread($fp, 4));
}
?>
or unpack('N', ...) for big-endianness.
[#17] zilinex at yahoo dot com [2004-09-01 23:12:33]
a cool function to converrt numbers to Persian numbers(utf-8)
origin: http://www.farsiweb.info/jalali/jalali.phps
function farsinum($str)
{
$ret = "";
for ($i = 0; $i < strlen($str); ++$i) {
$c = $str[$i];
if( $c >= '0' && $c <= '9' )
$out .= pack("C*", 0xDB, 0xB0 + $c);
else
$ret .= $c;
}
return $ret;
}
[#18] plutus at gmx dot de [2000-08-10 04:14:26]
Note that the the upper command in perl looks like this:
$binarydata = pack ("n v c*", 0x1234, 0x5678, 65, 66);
In PHP it seems that no whitespaces are allowed in the first parameter. So if you want to convert your pack command from perl -> PHP, don't forget to remove the whitespaces!