开发者

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">&lt;?php<开发者_运维知识库;br>$num&nbsp;</span>
    <span style="color: #007700">=&nbsp;</span>
    <span style="color: #0000BB">5</span>
    <span style="color: #007700">;<br></span>
    <span style="color: #0000BB">$location&nbsp;</span>
    <span style="color: #007700">=&nbsp;</span>
    <span style="color: #DD0000">'tree'</span>
    <span style="color: #007700">;<br><br></span>
    <span style="color: #0000BB">$format&nbsp;</span>
    <span style="color: #007700">=&nbsp;</span>
    <span style="color: #DD0000">'There&nbsp;are&nbsp;%d&nbsp;monkeys&nbsp;in&nbsp;the&nbsp;%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">,&nbsp;</span>
    <span style="color: #0000BB">$num</span>
    <span style="color: #007700">,&nbsp;</span>
    <span style="color: #0000BB">$location</span>
    <span style="color: #007700">);<br></span>
    <span style="color: #0000BB">?&gt;</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...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜