PHP Conference Japan 2024

highlight_string

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

highlight_string字串的語法高亮顯示

描述

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

使用 PHP 內建的語法高亮顯示器中定義的色彩,輸出或返回給定 PHP 程式碼的語法高亮 HTML 標記。

參數

string

要高亮顯示的 PHP 程式碼。這應包括開頭標籤。

return

將此參數設定為 true 以使此函式返回高亮顯示的程式碼。

回傳值

如果 return 設定為 true,則返回高亮顯示的程式碼作為字串,而不是直接輸出。否則,它將返回 true

變更日誌

版本 描述
8.4.0 回傳型別從 string|bool 變更為 string|true
8.3.0 產生的 HTML 已變更。

範例

範例 1 highlight_string() 範例

<?php
highlight_string
('<?php phpinfo(); ?>');
?>

上述範例將輸出

<code><span style="color: #000000">
<span style="color: #0000BB">&lt;?php phpinfo</span><span style="color: #007700">(); </span><span style="color: #0000BB">?&gt;</span>
</span>
</code>

在 PHP 8.3 中上述範例的輸出

<pre><code style="color: #000000"><span style="color: #0000BB">&lt;?php phpinfo</span><span style="color: #007700">(); </span><span style="color: #0000BB">?&gt;</span></code></pre>

注意事項

注意:

當使用 return 參數時,此函式會使用內部輸出緩衝,因此不能在 ob_start() 回呼函式中使用。

產生的 HTML 標記可能會變更。

參見

新增註解

使用者貢獻的註解 29 則註解

stanislav dot eckert at vizson dot de
8 年前
您可以像這樣變更高亮顯示的色彩

<?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");
?>

如您在上面的範例中所見,您甚至可以新增額外的樣式,例如粗體文字,因為這些值會直接設定到 DOM 屬性 "style"。

此外,此函式僅在高亮顯示以 "<?php" 前綴開頭的文字。但是此函式也可以高亮顯示其他類似的格式 (不是完美,但總比沒有好),例如 HTML、XML、C++、JavaScript 等。我使用以下函式來高亮顯示不同的檔案類型,效果還不錯

<?php
function highlightText($text)
{
$text = trim($text);
$text = highlight_string("<?php " . $text, true); // highlight_string() 需要開頭 PHP 標籤,否則不會為文字著色
$text = trim($text);
$text = preg_replace("|^\\<code\\>\\<span style\\=\"color\\: #[a-fA-F0-9]{0,6}\"\\>|", "", $text, 1); // 移除前綴
$text = preg_replace("|\\</code\\>\$|", "", $text, 1); // 移除尾碼 1
$text = trim($text); // 移除換行符號
$text = preg_replace("|\\</span\\>\$|", "", $text, 1); // 移除尾碼 2
$text = trim($text); // 移除換行符號
$text = preg_replace("|^(\\<span style\\=\"color\\: #[a-fA-F0-9]{0,6}\"\\>)(&lt;\\?php&nbsp;)(.*?)(\\</span\\>)|", "\$1\$3\$4", $text); // 移除自訂新增的 "<?php "

return $text;
}
?>

請注意,它也會移除 <code> 標籤,因此您可以直接取得格式化的文字,這讓您有更大的自由來處理結果。

我個人建議結合這兩件事,以便為具有不同高亮顯示色彩組的不同檔案類型提供良好的高亮顯示函式

<?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() 函式需要開頭的 PHP 標籤,否則不會將文字著色
$text = trim($text);
$text = preg_replace("|^\\<code\\>\\<span style\\=\"color\\: #[a-fA-F0-9]{0,6}\"\\>|", "", $text, 1); // 移除前綴
$text = preg_replace("|\\</code\\>\$|", "", $text, 1); // 移除後綴 1
$text = trim($text); // 移除換行符號
$text = preg_replace("|\\</span\\>\$|", "", $text, 1); // 移除後綴 2
$text = trim($text); // 移除換行符號
$text = preg_replace("|^(\\<span style\\=\"color\\: #[a-fA-F0-9]{0,6}\"\\>)(&lt;\\?php&nbsp;)(.*?)(\\</span\\>)|", "\$1\$3\$4", $text); // 移除自訂加入的 "<?php "

return $text;
}
?>
www.phella.net
17 年前
當你在網站上引用高亮的 PHP 程式碼時,你需要跳脫引號。如果你引用很多,可能會很煩人。這裡有一個小程式碼片段,說明如何使引用整潔乾淨。像這樣編寫程式碼:

<?code()?>
$string = '這裡我放置我的程式碼';
<?code()?>

在其他地方定義函式

<?
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 年前
如果你想要使用類別而不是內聯樣式,這是高亮程式碼的最佳方式:

<?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", // 將 <br> 替換為換行符號
str_replace(
[
// 前導的 <?php 垃圾文字
"<span style=\"color: c-default\">\n&lt;?php&nbsp;",
"<code>",
"</code>"
],
"",
highlight_string("<?php " . $text, true)
)
)
);

// 替換顏色
$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;
}
?>

產生看起來像這樣的輸出:

<span class="c-keyword">if(</span>condition<span class="c-keyword">){
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;echo&nbsp;</span><span class="c-string">"HTML&nbsp;here"</span><span class="c-keyword">;
}</span>

希望這對您有幫助。
admin [at] develogix [dot] com
19 年前
我一直在開發一個可以取代 highlight_string() 函式的替代方案;以下是我目前想到的:

<?
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);
}
// 刪除第一個 <span style="color:#000000;"> 和對應的 </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('&nbsp;', 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;}
}
?>

這個函式會透過將 font 標籤替換為 span 標籤來輸出有效的 XHTML 1.1 程式碼。您也可以指定是否要傳回或輸出、輸出列計數、列計數的顏色以及起始列計數數字。

用法
<?
// $str = 包含 php 的字串
// $return = true (傳回) / false (輸出)
// 預設為 false
// $counting = true (計數) / false (不計數)
// 預設為 true
// $start = 起始計數數字
// 預設為 '1'
// $color = 列計數顏色,前面加上 #
// 預設為 '#666'
get_sourcecode_string($str, $return, $counting, $start, $color);
?>
vouksh at vouksh dot info
19 年前
完全運作、準備好 XHTML 1.1 的 xhtml_highlight 函式。我加入了 stripslashes,因為我遇到了一些沒有它的問題。保留它應該是安全的,但如果您遇到問題,請隨時將它移除。

<?
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 年前
我讀了來自 "stanislav dot eckert at vizson dot de" 的筆記,我非常喜歡他創建的函數。
為了我的用途,我做了一些改編,使該函數更加實用,並允許一次傳遞和多個參數。我也修改了 <code> 元素的樣式,使其具有黑色背景和邊距。

<?php

// highlight_string 和 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() 需要 PHP 開啟標籤,否則不會對文本進行顏色化
$output = preg_replace("|\\<code\\>|", "<code style='background-color: #000000; padding: 10px; margin: 10px; display: block; font: 12px Consolas;'>", $output, 1); // 編輯前綴
$output = preg_replace("|(\\<span style\\=\"color\\: #[a-fA-F0-9]{0,6}\"\\>)(&lt;\\?php&nbsp;)(.*?)(\\</span\\>)|", "\$1\$3\$4", $output); // 移除自訂新增的 "<?php "
echo $output;
}
} catch (
Exception $e) {
echo
$e->getMessage();
}
}

// 一次除錯多個變數。
$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 年前
替代的 XML 語法高亮顯示。

<?php
function xml_highlight($s)
{
$s = htmlspecialchars($s);
$s = preg_replace("#&lt;([/]*?)(.*)([\s]*?)&gt;#sU",
"<font color=\"#0000FF\">&lt;\\1\\2\\3&gt;</font>",$s);
$s = preg_replace("#&lt;([\?])(.*)([\?])&gt;#sU",
"<font color=\"#800000\">&lt;\\1\\2\\3&gt;</font>",$s);
$s = preg_replace("#&lt;([^\s\?/=])(.*)([\[\s/]|&gt;)#iU",
"&lt;<font color=\"#808000\">\\1\\2</font>\\3",$s);
$s = preg_replace("#&lt;([/])([^\s]*?)([\s\]]*?)&gt;#iU",
"&lt;\\1<font color=\"#808000\">\\2</font>\\3&gt;",$s);
$s = preg_replace("#([^\s]*?)\=(&quot;|')(.*)(&quot;|')#isU",
"<font color=\"#800080\">\\1</font>=<font color=\"#FF00FF\">\\2\\3\\4</font>",$s);
$s = preg_replace("#&lt;(.*)(\[)(.*)(\])&gt;#isU",
"&lt;\\1<font color=\"#800080\">\\2\\3\\4</font>&gt;",$s);
return
nl2br($s);
}
?>
manithu at fahr-zur-hoelle dot org
20 年前
此函數將返回高亮顯示且符合 xhtml 1.1 標準的程式碼(將 <font> 替換為 <span> 元素,並將顏色替換為 style 屬性)

<?php

function xhtml_highlight($str) {
$str = highlight_string($str, true);
// 替換 <code><font color=""></font></code>
$str = preg_replace('#<font color="([^\']*)">([^\']*)</font>#', '<span style="color: \\1">\\2</span>', $str);
// 替換其他 <font> 元素
return preg_replace('#<font color="([^\']*)">([^\']*)</font>#U', '<span style="color: \\1">\\2</span>', $str);
}

?>
gaggge at gmail dot com
19 年前
這是一個用於高亮顯示來自 mysql 資料庫的 bbcode 風格 PHP 程式碼的小函數。
(例如這樣:[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 年前
這個函數將每個空格替換為 html 程式碼 &nbsp;(不換行空格)
這不是很好,因為文字不會換行,並導致很大的寬度
例如,在一個有邊框的 div 中,文字將會超出邊框

我的解決方案
echo str_replace("&nbsp;", " ",highlight_string("奮起吧,祖國的兒女們",true));
echo str_replace("&nbsp;", " ",highlight_file("test.php",true));
stalker at ruun dot de
18 年前
給 vouksh:我稍微擴展了你的函數

<?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 年前
這是 Dimitry 的 xml_highlight 函數的改進版本。
我修復了一個會替換標籤名稱第一個字元的錯誤,
並新增了一行,將 Tab 鍵和空格替換為
不斷行空格符號,以保持縮排。

<?
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","&nbsp;&nbsp;",$s);
$s = str_replace(" ","&nbsp;",$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 年前
文件對於第一個參數的說明是「要強調顯示的 PHP 程式碼。這應該包含開頭標籤。」。但似乎程式碼不僅應該,而且*必須*以 PHP 的開頭標籤開始,否則函數仍會修改但不會強調顯示程式碼。
Mean^_^
15 年前
[由 danbrown AT php DOT net 編輯:以下註解包含使用者提供的語法強調顯示器版本。]

<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);
?>

由 mean
分享想法。
祝你好運 ^_^
fsx dot nr01 at gmail dot com
16 年前
這是從 '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('(&lt;\?php&nbsp;)+', '', 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 年前
好吧,這是我寫的一個小東西,它可以強調顯示 HTML 程式碼...在接下來的幾天裡它會經過許多更改......直到那時 =) 請享用

<?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 = "&lt;<span class='HTMLComment'>";
for(
$position+=1;$position < strlen($this->content) && $this->content[$position] != ">" ;$position++){
$buffer.= $this->content[$position];
}
$buffer .= "</span>&gt;";
$this->colorized .= $buffer;
return
$position;
}
function
colorTag($position){
$buffer = "&lt;<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>&gt;";
$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 風格
\**********************/
/*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>
wm at tellinya dot com
16 年前
我想建立一個更好的函數,並從關鍵字 span class 中排除運算符 {}=-。我也想將 PHP 程式碼中使用的函數直接連結到 PHP 網站。
已進行了更多變更和調整,輸出效果更好!

在此處尋找函數
http://www.tellinya.com/art2/262/highligh-php-syntax/
並永久放棄舊的 PHP 函數。
已在 PHP 5.2.0 上測試和建置。

期待任何意見。
zer0
19 年前
關於我下面的程式碼

很抱歉,我完全忘記了 `str_ireplace` 函式是 PHP 5 才有的。而且,我還漏看了一個錯誤(熬夜太多了 ;)。這是修正後的程式碼:

<?php
function highlight_code($code, $inline=false, $return=false) // 為了支援 php 4 之前的版本來擷取高亮顯示
{
(string)
$highlight = "";
if (
version_compare(PHP_VERSION, "4.2.0", "<") === 1 )
{
ob_start(); // 開始輸出緩衝來擷取高亮顯示的內容
highlight_string($code);
$highlight = ob_get_contents(); // 擷取輸出
ob_end_clean(); // 清除緩衝
}
else
{
$highlight=highlight_string($code, true);
}

# 使用 preg_replace 讓 PHP 4 也能使用
if ( $inline === true )
$highlight=preg_replace("/<code>/i","<code class=\"inline\">",$highlight);
else
$highlight=preg_replace("/<code>/i","<code class=\"block\">",$highlight);

if (
$return === true )
{
return
$highlight;
}
else
{
echo
$highlight;
}
}
?>
Sam Wilson
19 年前
manithu 在 fahr-zur-hoelle dot org 漏了一個地方:修正換行標籤。加入以下程式碼應該就可以了。

<?php
$str
= str_replace("<br>", "<br />", $str);
?>
bpgordon at gmail dot com
19 年前
關於 dleavitt AT ucsc DOT edu 的評論

您可能會想使用 `md5($html_string)` 而不是 "piggusmaloy",這是一個比較好的程式設計習慣。以防萬一 "$html_string" 中真的有 "piggusmaloy" 這個字串。
trixsey at animania dot nu
19 年前
我寫的一個好用的函式。語法著色、列號、表格中每列不同的背景顏色。

<?
function showCode($code) {
$html = highlight_string($code, true);
$html = str_replace("\n", "", $html);
$rows = explode("<br />", $html);

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

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

if($i==1) {
$row_num[] = "<tr><td><code><font color=\"#000000\"><code>$i</code></font>\t$row</code></td></tr>";
}

if($i!=1) {
if(is_int($i/2)) {
$row_num[] = "<tr bgcolor=\"#F9F9F9\"><td><code><font color=\"#000000\">$i</font>\t$row</code></td></tr>";
} else {
$row_num[] = "<tr><td><code><font color=\"#000000\">$i</font>\t$row</code></td></tr>";
}
}

$i++;
}
return "<pre>\nFilename: <b>$_GET[file]</b>\n<table
style=\"border:1px #000000 solid\">".implode($row_num)."</table></pre>";
}
?>
support at superhp dot de
19 年前
這個函式可以讓您高亮顯示 PHP 程式碼並加上行號

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

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

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

$header='<table border="0" cellpadding="0" cellspacing="0" width="95%" style="border-style: solid; border-width:1px; border-color: white black black white">
<tr>
<td width="100%" colspan="2" style="border-style: solid; border-width:1px; border-color: white; background-color: #99ccff; font-family:Arial; color:white; font-weight:bold;">Php-Code:</td>
</tr>
<tr>
<td width="3%" valign="top" style="background-color: #99ccff; border-style: solid; border-width:1px; border-color: white;"><code>'
.$line.'</code></td>
<td width="97%" valign="top" style="background-color: white;"><div style="white-space: nowrap; overflow: auto;"><code>'
;

$footer=$Code.'</div></code></td>
</tr>
</table>'
;

return
$header.$footer;
}
?>
admin at bwongar dot com
19 年前
我從其他 XHTML_highlight 函式中沒有得到預期的結果,所以我開發了自己的函式,而且效率更高。舊的函式使用 preg_replace 將標籤的內容替換為 span 標籤內。我的函式中唯一的 preg_replace 是提取 color 屬性,並將其放置在 str_replace'd 的 span 標籤內。

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

?>
peter at int8 dot com
18 年前
這裡沒有提到,但程式碼片段中似乎必須包含 PHP 開啟和關閉標籤。
<?php highlight_string("<? \$var = 15; ?>"); ?>
有效,而
<?php highlight_string("\$var = 15;"); ?>
則無效。這對我們這些想要顯示小型程式碼片段的人來說很不幸,但情況就是這樣。如果我沒記錯的話,這個函式的早期版本沒有這個要求。
supremacy2k at gmail dot com
17 年前
簡化了 vanessaschissato at gmail dot com 於 2006 年 10 月 17 日 05:04 發布的函式。

因為它在保持程式碼完整方面有問題。(它移除了 /* )

function showCode($code) {
$code = highlight_string($code, true);
$code = explode("<br />", $code);

$i = "1";
foreach ($code as $line => $syntax) {
echo "<font color='black'>".$i."</font> ".$syntax."<br>";
$i++;
}
}
tyler dot reed at brokeguysinc dot com
18 年前
這是一小段程式碼,我用來顯示檔案的原始碼,我從另一個 PHP 函式頁面上找到的範例中提取了部分想法。

這段程式碼會取得一個 PHP 檔案並將其高亮顯示,並在旁邊放置一個行號。非常適合即時偵錯。

<?php
// 將檔案讀取到陣列中
$lines = file('index.php');

// 迴圈瀏覽我們的陣列,將 HTML 原始碼顯示為 HTML 原始碼;還有行號。
echo('<table border=0 cellpadding=0 cellspacing=0>');
foreach (
$lines as $line_num => $line) {
echo(
'<tr>');
echo(
'<td bgcolor = "#cccccc">');
echo(
'<code>' . ($line_num + 1) . '</code>');
echo(
'</td>');
echo(
'<td>');
highlight_string($line);
echo(
'</td>');
echo(
'</tr>');
}

?>
joshuaeasy4u at gmail dot com
11 年前
<?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('(&lt;\?php&nbsp;)+','',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>';
}
?>
zero
19 年前
在某些情況下,我發現將 `highlight_string` 的格式設定為段落中的內嵌 `<code>...</code> 很有用,而其他時候,則作為示範多行程式碼的區塊。我製作這個函數來協助處理。

<?php
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("<code>","<code class=\"inline\">",$highlight);
else
$highlight=str_ireplace("<code>","<code class=\"block\">",$highlight);


if (
$return === true )
{
return
$highlight;
}
else
{
echo
$highlight;
}
}
?>
Dmitry S
16 年前
簡單的 XML 語法高亮顯示。

<?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);
}
?>
To Top