I have a custom php website where I want to post php snippets but I'd like to have highlight my source code. I tried via pure php using Geshi (https://github.com/GeSHi/geshi-1.0) but it's not as I wanted, so I'm interested in other library like Google Code Prettify (https://github.com/google/code-prettify) but I don't know how using this javascript library.

<link rel="stylesheet" type="text/css" media="all" href="gcp/prettify.css">
<script src="gcp/prettify.js" type="text/javascript"></script>

<body onload="prettyPrint()">

$body = preg_replace('#\[code\](.*)\[/code\]#isU', '<div class="code"><span class="xcode"><code class="prettyprint">\1</code></span></div>', $body);

Am I using correctly Google Code Prettify?

Another question, am I using the correct Regular Expression in the bbcode?

Any help is appreciated!

example

有帮助吗?

解决方案

A better function to use would be preg_replace_callback() for this as you can then pass the matched text to a callback function for reformatting.

Here's an example implementation: (this may need some tweaking but you should get the idea)

function code_tag_replace( $matches ) {
    $ret  = '<TABLE WIDTH="100%" CELLSPACING="0" CELLPADDING="10" CLASS="code" BORDER="0"><TR><TD><SPAN CLASS="xcode">';
    $ret .= SyntaxHighlight::process( $matches[1] );
    $ret .= '</SPAN></TD></TR></TABLE>';
    return $ret;
}
$body = preg_replace_callback(
    '#\[code\](.*)\[/code\]#isU',
    'code_tag_replace',
    $body
);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top