如何制作基于web的代码编辑器


How to make web based code editor

我一直在尝试创建一个代码片段网站,我只需要一个漂亮的带有语法高亮的开源代码编辑器。我发现http://ace.c9.io/但当我通过编辑器脚本传递PHP时,它似乎不起作用;

通过CodeEditor运行的PHP代码:

    <div id="editor"><?php echo 'test'; ?></div>
<script>
    var editor = ace.edit("editor");
    editor.setTheme("ace/theme/monokai");
    editor.getSession().setMode("ace/mode/javascript");
    editor.setReadOnly(true);
</script>

它在编辑器框中显示"测试"。

如果我使用此代码通过Javascript,它会起作用:

<div id="editor">function foo(items) {
    var x = "All this is syntax highlighted";
    return x;
}</div>

<script>
    var editor = ace.edit("editor");
    editor.setTheme("ace/theme/monokai");
    editor.getSession().setMode("ace/mode/javascript");
</script>

我需要一个可以方便地输入任何文本/代码并适当突出显示它的程序。

您需要对<>字符进行编码,这样它们就不会被解释为HTML标记

<div id="editor">&lt;?php echo 'test'; ?&gt;</div>

如果您使用PHP创建页面,则可以使用htmlentities()执行此编码。如果使用jQuery,$("#editor").text(code)将对其进行正确编码(使用.html()将解释HTML标记)。

如果您在.php文件上运行,它将在编辑器框中显示测试。您必须进行html编码才能对其进行转义。

<?php echo htmlspecialchars('<?php echo ''test''; ?>'); ?>