Thursday, March 3, 2011

PHP function which does syntax color parsing for multiple languages?

I'm doing a PHP site which displays code examples in various languages (C#, PHP, Perl, Ruby, etc.). Are there any PHP functions which add syntax coloring for these and other languages?

If not, I would at least like to find that one built-in PHP function which does syntax coloring for PHP code, can't find it anymore. Thanks.

From stackoverflow
  • Why not do the syntax coloration in the client side?

    Use prettify.js, its really versatile, Google Code and StackOverflow use it!

    Check the test page for the supported languages.

  • You'd probably be better off formatting it in javascript actually. There are a few mature javascript syntax colors.

  • For highlighting PHP use highlight_string(). (This may work OK with other languages as well.)

    Edit: This function requires that the string start with the PHP opening tag. What I did on my site to get around this was I passed something like "<?php\n$code\n?>" to the highlight_string() function and then used regex to strip out the starting and ending tags that I had added in. This method has worked pretty well for highlighting C/C++, Scheme, and Java (and PHP that doesn't have the <?php ?> tags.)

  • Try googling pretty-print.

    And for the php function, you want this.

  • As already mentioned Google prettify.js is really good, but if you want to do it on the server in PHP you could try looking at Pear Text Highlighter

0 comments:

Post a Comment