Javascript - Color example code
Is there a javascript plugin available that will color example code to make it look as it does in a text editor? Using the php.net prinf page as an example, I want to convert this:
<code>
<?php<br>
$num = 5;<br>
$location = 'tree';<br>
$format = 'There are %d monkeys in the %s';<br>
printf($format, $num, $location);<br>
?>
</code>
to this
<code>
<span style="color: #000000">
<span style="color: #0000BB"><?php<开发者_运维知识库;br>$num </span>
<span style="color: #007700">= </span>
<span style="color: #0000BB">5</span>
<span style="color: #007700">;<br></span>
<span style="color: #0000BB">$location </span>
<span style="color: #007700">= </span>
<span style="color: #DD0000">'tree'</span>
<span style="color: #007700">;<br><br></span>
<span style="color: #0000BB">$format </span>
<span style="color: #007700">= </span>
<span style="color: #DD0000">'There are %d monkeys in the %s'</span>
<span style="color: #007700">;<br></span>
<span style="color: #0000BB">printf</span>
<span style="color: #007700">(</span>
<span style="color: #0000BB">$format</span>
<span style="color: #007700">, </span>
<span style="color: #0000BB">$num</span>
<span style="color: #007700">, </span>
<span style="color: #0000BB">$location</span>
<span style="color: #007700">);<br></span>
<span style="color: #0000BB">?></span>
</span>
See google-code-prettify
https://github.com/cloudhead/hijs
https://github.com/rpflorence/hilite
Neither depend on a library.
Edit: Sorry, thought you wanted to highlight JavaScript (read too fast). hilite
still needs PHP added as a language, but you could add it. Here's a solid one:
http://code.google.com/p/syntaxhighlighter/
That's pretty difficult without a library... but not much too difficult. You could easily do most of it with regular expressions such as:
\$\w+
Which would match all variables. Of course, you'd have to filter out those within single-quoted strings. So the basic strategy is - use regex as much as possible, then filter out the exceptions (such as escaping) using manual string parsing with loops. Just look at the methods of the String
type - you'll use charAt()
and insert()
probably for the manual manipulation, and String.search()
for the regular expressions...
精彩评论