PHP 语法高亮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/230270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP syntax highlighting
提问by Konrad Rudolph
I'm searching for a PHP syntax highlighting enginethat can be customized (i.e. I can provide my own tokenizersfor new languages) and that can handle several languages simultaneously(i.e. on the same output page). This engine has to work well together with CSS classes, i.e. it should format the output by inserting <span>elements that are adorned with classattributes. Bonus points for an extensible schema.
我正在寻找一个可以定制的PHP 语法高亮引擎(即我可以为新语言提供我自己的标记器)并且可以同时处理多种语言(即在同一个输出页面上)。这个引擎必须与CSS 类很好地协同工作,即它应该通过插入<span>装饰有class属性的元素来格式化输出。可扩展架构的加分点。
I do notsearch for a client-side syntax highlighting script (JavaScript).
我不搜索客户端语法高亮脚本 (JavaScript)。
So far, I'm stuck with GeSHi. Unfortunately, GeSHi fails abysmally for several reasons. The main reason is that the different language files define completely different, inconsistent styles. I've worked hours trying to refactor the different language definitions down to a common denominator but since most definition files are in themselves quite bad, I'd finally like to switch.
到目前为止,我坚持使用GeSHi。不幸的是,GeSHi 失败的原因有很多。主要原因是不同的语言文件定义了完全不同的、不一致的样式。我花了好几个小时试图将不同的语言定义重构为一个共同点,但由于大多数定义文件本身就很糟糕,我最终想切换。
Ideally, I'd like to have an API similar to CodeRay, Pygmentsor the JavaScript dp.SyntaxHighlighter.
理想情况下,我想要一个类似于CodeRay、Pygments或 JavaScript dp.SyntaxHighlighter 的 API。
Clarification:
澄清:
I'm looking for a code highlighting software written inPHP, not forPHP (since I need to use it from inside PHP).
我在找编写的代码高亮软件在PHP中,没有对PHP(因为我需要用它从内PHP)。
回答by Konrad Rudolph
Since no existing tool satisfied my needs, I wrote my own. Lo and behold:
由于没有现有工具满足我的需求,我自己编写了。瞧:
Hyperlight
超光
Usage is extremely easy: just use
使用非常简单:只需使用
<?php hyperlight($code, 'php'); ?>
to highlight code. Writing new language definitions is relatively easy, too – using regular expressions and a powerful but simple state machine. By the way, I still needa lot of definitions so feel free to contribute.
突出显示代码。编写新的语言定义也相对容易——使用正则表达式和强大但简单的状态机。顺便说一句,我仍然需要很多定义,所以请随意贡献。
回答by micahwittman
[I marked this answer as Community Wikibecause you're specifically notlooking for Javascript]
[我将此答案标记为Community Wiki,因为您不是在寻找 Javascript]
http://softwaremaniacs.org/soft/highlight/is a PHP (plus the following list of other languages supported) syntax highlighting library:
http://softwaremaniacs.org/soft/highlight/是一个 PHP(加上以下支持的其他语言列表)语法高亮库:
Python, Ruby, Perl, PHP, XML, HTML, CSS, Django, Javascript, VBScript, Delphi, Java, C++, C#, Lisp, RenderMan (RSL and RIB), Maya Embedded Language, SQL, SmallTalk, Axapta, 1C, Ini, Diff, DOS .bat, Bash
Python、Ruby、Perl、PHP、XML、HTML、CSS、Django、Javascript、VBScript、Delphi、Java、C++、C#、Lisp、RenderMan(RSL 和 RIB)、Maya 嵌入式语言、SQL、SmallTalk、Axapta、1C、Ini , 差异, DOS .bat, Bash
It uses <span class="keyword">style markup.
它使用<span class="keyword">样式标记。
It has also been integrated in the dojo toolkit(as a dojox project: dojox.lang.highlight)
它也已集成到dojo 工具包中(作为dojox项目:dojox.lang.highlight)
Though not the most popular way to run a webserver, strictly speaking, Javascript is not only implemented on the client-side, but there are also Server-Side Javascript engine/platform combinations too.
虽然不是最流行的运行网络服务器的方式,但严格来说,Javascript 不仅在客户端实现,而且还有服务器端 Javascript 引擎/平台组合。
回答by Taufik Nurrohman
I found this simple generic syntax highlighter written in PHP hereand modified it a bit:
我在这里找到了用 PHP 编写的这个简单的通用语法荧光笔,并对其进行了一些修改:
<?php
/**
* Original => http://phoboslab.org/log/2007/08/generic-syntax-highlighting-with-regular-expressions
* Usage => `echo SyntaxHighlight::process('source code here');`
*/
class SyntaxHighlight {
public static function process($s) {
$s = htmlspecialchars($s);
// Workaround for escaped backslashes
$s = str_replace('\\','\\<e>', $s);
$regexp = array(
// Comments/Strings
'/(
\/\*.*?\*\/|
\/\/.*?\n|
\#.[^a-fA-F0-9]+?\n|
\<\!\-\-[\s\S]+\-\-\>|
(?<!\\)".*?(?<!\\)"|
(?<!\\)\'(.*?)(?<!\\)\'
)/isex'
=> 'self::replaceId($tokens,\'\')',
// Punctuations
'/([\-\!\%\^\*\(\)\+\|\~\=\`\{\}\[\]\:\"\'<>\?\,\.\/]+)/'
=> '<span class="P"></span>',
// Numbers (also look for Hex)
'/(?<!\w)(
(0x|\#)[\da-f]+|
\d+|
\d+(px|em|cm|mm|rem|s|\%)
)(?!\w)/ix'
=> '<span class="N"></span>',
// Make the bold assumption that an
// all uppercase word has a special meaning
'/(?<!\w|>|\#)(
[A-Z_0-9]{2,}
)(?!\w)/x'
=> '<span class="D"></span>',
// Keywords
'/(?<!\w|$|\%|\@|>)(
and|or|xor|for|do|while|foreach|as|return|die|exit|if|then|else|
elseif|new|delete|try|throw|catch|finally|class|function|string|
array|object|resource|var|bool|boolean|int|integer|float|double|
real|string|array|global|const|static|public|private|protected|
published|extends|switch|true|false|null|void|this|self|struct|
char|signed|unsigned|short|long
)(?!\w|=")/ix'
=> '<span class="K"></span>',
// PHP/Perl-Style Vars: $var, %var, @var
'/(?<!\w)(
($|\%|\@)(\->|\w)+
)(?!\w)/ix'
=> '<span class="V"></span>'
);
$tokens = array(); // This array will be filled from the regexp-callback
$s = preg_replace(array_keys($regexp), array_values($regexp), $s);
// Paste the comments and strings back in again
$s = str_replace(array_keys($tokens), array_values($tokens), $s);
// Delete the "Escaped Backslash Workaround Token" (TM)
// and replace tabs with four spaces.
$s = str_replace(array('<e>', "\t"), array('', ' '), $s);
return '<pre><code>' . $s . '</code></pre>';
}
// Regexp-Callback to replace every comment or string with a uniqid and save
// the matched text in an array
// This way, strings and comments will be stripped out and wont be processed
// by the other expressions searching for keywords etc.
private static function replaceId(&$a, $match) {
$id = "##r" . uniqid() . "##";
// String or Comment?
if(substr($match, 0, 2) == '//' || substr($match, 0, 2) == '/*' || substr($match, 0, 2) == '##' || substr($match, 0, 7) == '<!--') {
$a[$id] = '<span class="C">' . $match . '</span>';
} else {
$a[$id] = '<span class="S">' . $match . '</span>';
}
return $id;
}
}
?>
Demo:http://phpfiddle.org/lite/code/1sf-htn
演示:http : //phpfiddle.org/lite/code/1sf-htn
Update
更新
I just created a PHP port of my own JavaScript generic syntax highlighter here → https://github.com/taufik-nurrohman/generic-syntax-highlighter/blob/master/generic-syntax-highlighter.php
我刚刚在这里创建了我自己的 JavaScript 通用语法荧光笔的 PHP 端口 → https://github.com/taufik-nurrohman/generic-syntax-highlighter/blob/master/generic-syntax-highlighter.php
How to use:
如何使用:
<?php require 'generic-syntax-highlighter.php'; ?>
<pre><code><?php echo SH('<div class="foo"></div>'); ?></code></pre>
回答by Tom Haigh
It might be worth looking at Pear_TextHighlighter(documentation)
可能值得一看Pear_TextHighlighter(文档)
I think it won't by default output html exactly how you want it, but it does provide extensive capabilities for customisation (i.e. you can create different renderers/parsers)
我认为默认情况下它不会按照您想要的方式输出 html,但它确实提供了广泛的自定义功能(即您可以创建不同的渲染器/解析器)
回答by Tom Haigh
I had exactly the the same problem but as I was very short on time and needed really good code coverage I decided to write a PHP wrapper around Pygmentslibrary.
我遇到了完全相同的问题,但由于我的时间很短并且需要非常好的代码覆盖率,我决定围绕Pygments库编写一个 PHP 包装器。
It's called PHPygmentizator. It's really simple to use. I wrote a very basic manual. As PHP is Web Development language primarily, I subordinated the structure to that fact and made it very easy to implement in almost any kind of website.
它被称为PHPygmentizator。使用起来真的很简单。我写了一个非常基本的手册。由于 PHP 主要是 Web 开发语言,因此我将结构从属于这一事实,并使其在几乎任何类型的网站中都非常容易实现。
It supports configuration filesand if that isn't enough and somebody needs to modify stuff in the process it also fires events.
它支持配置文件,如果这还不够并且有人需要在过程中修改内容,它还会触发events。
Demo of how it works can be found on basically any post of my blog which contains source code, this one for example.
基本上可以在我博客的任何包含源代码的帖子中找到它如何工作的演示,例如这个。
With default config you can just provide it a string in this format:
使用默认配置,您可以只提供以下格式的字符串:
Any text here.
[pygments=javascript]
var a = function(ar1, ar2) {
return null;
}
[/pygments]
Any text.
So it highlights code between tags (tags can be customized in configuration file) and leaves the rest untouched.
所以它突出了标签之间的代码(标签可以在配置文件中自定义),其余部分保持不变。
Additionally I already made a Syntax recognition library(it uses algorithm which would probably be classified as Bayesian probability) which automatically recognizes which language code block is written in and can easily be hooked to one of PHPygmentizatorevents to provide automatic language recognition. I will probably make it public some time this week since I need to beautify the structure a bit and write some basic documentation. If you supply it with enough "learning" data it recognizes languages amazingly well, I tested even minified javascripts and languages which have similar keywords and structures and it has never made a mistake.
此外,我已经制作了一个语法识别库(它使用的算法可能会被归类为贝叶斯概率),它可以自动识别编写的语言代码块,并且可以轻松地连接到PHPygmentizator事件之一以提供自动语言识别。我可能会在本周某个时间将其公之于众,因为我需要稍微美化一下结构并编写一些基本文档。如果你为它提供足够的“学习”数据,它可以非常好地识别语言,我甚至测试了具有相似关键字和结构的缩小的 javascript 和语言,并且它从未犯过错误。
回答by Rob Prouse
Another option is to use the GPL Highlight GUIprogram by Andre Simon which is available for most platforms. It converts PHP (and other languages) to HTML, RTF, XML, etc. which you can then cut and paste into the page you want. This way, the processing is only done once.
另一种选择是使用Andre Simon的 GPL Highlight GUI程序,该程序可用于大多数平台。它将 PHP(和其他语言)转换为 HTML、RTF、XML 等,然后您可以将其剪切并粘贴到您想要的页面中。这样,处理只进行一次。
The HTML is also CSS based, so you can change the style as you please.
HTML 也是基于 CSS 的,因此您可以随意更改样式。
Personally, I use dp.SyntaxHighlighter, but that uses client side Javascript, so it doesn't meet your needs. It does have a nice Windows Live plugin though which I find useful.
就个人而言,我使用dp.SyntaxHighlighter,但它使用客户端 Javascript,因此它不能满足您的需求。它确实有一个不错的 Windows Live 插件,但我觉得它很有用。
回答by Ghostff
PHP PrettifyWorks fine so far, And has more customization than highlight_string
PHP Prettify到目前为止工作正常,并且比highlight_string有更多的自定义
回答by Craig
A little late to chime in here, but I've been working on my own PHP syntax highlighting library. It is still in its early stages, but I am using it for all code samples on my blog.
在这里发言有点晚了,但我一直在研究我自己的 PHP 语法高亮库。它仍处于早期阶段,但我将它用于我博客上的所有代码示例。
Just checked out Hyperlight. It looks pretty cool, but it is doing some pretty crazy stuff. Nested loops, processing line by line, etc. The core class is over 1000 lines of code.
刚刚检查了 Hyperlight。它看起来很酷,但它正在做一些非常疯狂的事情。嵌套循环,逐行处理等,核心类1000多行代码。
If you are interested in something simple and lightweight check out Nijikodo: http://www.craigiam.com/nijikodo
如果您对简单而轻便的东西感兴趣,请查看 Nijikodo:http://www.craigiam.com/nijikodo
回答by Gabor de Mooij
Why not use PHP's build-in syntax highlighter?
为什么不使用 PHP 的内置语法荧光笔?
回答by Mathias Bynens
Krijn Hoetmer's PHP Highlighterprovides a completely customizable PHP class to highlight PHP syntax. The HTML it generates, validates under a strict doctype, and is completely stylable with CSS.
Krijn Hoetmer 的PHP Highlighter提供了一个完全可定制的 PHP 类来突出显示 PHP 语法。它生成的 HTML 在严格的文档类型下进行验证,并且完全可以使用 CSS 进行样式化。

