man page 表示如果 infile 被省略,它会从 stdin 读取,如果 outfile 被省略,它会写入 stdout。
所以你可以在命令行输入:
$ pymentize -l php -f html
<?php
echo 'hello world!';
^D // type: Control+D
pymentize 会输出:
<div class="highlight"><pre><span class="cp"><?php</span>
<span class="k">echo</span> <span class="s1">'hello world!'</span><span class="p">; </span>
</pre></div>
如果您使用 PHP 运行它,您必须使用 proc_open() 启动 pygmentize,因为您必须将其写入标准输入。下面是一个简短的例子:
echo pygmentize('<?php echo "hello world!\n"; ?>');
/**
* Highlights a source code string using pygmentize
*/
function pygmentize($string, $lexer = 'php', $format = 'html') {
// use proc open to start pygmentize
$descriptorspec = array (
array("pipe", "r"), // stdin
array("pipe", "w"), // stdout
array("pipe", "w"), // stderr
);
$cwd = dirname(__FILE__);
$env = array();
$proc = proc_open('/usr/bin/pygmentize -l ' . $lexer . ' -f ' . $format,
$descriptorspec, $pipes, $cwd, $env);
if(!is_resource($proc)) {
return false;
}
// now write $string to pygmentize's input
fwrite($pipes[0], $string);
fclose($pipes[0]);
// the result should be available on stdout
$result = stream_get_contents($pipes[1]);
fclose($pipes[1]);
// we don't care about stderr in this example
// just checking the return val of the cmd
$return_val = proc_close($proc);
if($return_val !== 0) {
return false;
}
return $result;
}
顺便说一句,pygmentize 是很酷的东西!我也在用它:)