首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用代码高亮工具显示代码

使用代码高亮工具显示代码
EN

Stack Overflow用户
提问于 2013-08-23 21:46:12
回答 2查看 120关注 0票数 4

我想插入一些编程代码与描述一样,一个教程网站。

以下是HTML代码的示例代码:

代码语言:javascript
复制
 $code = "
 <p>This is introduction to HTML </p>

  [code]
<html> 
<head>
    <title>This is sample descriptions</title>
</head>
<body>
    <form method='post' action='index.php'>
        <input type='text' name='username' value=''>
        <input type='password' name='password' value=''>
        <input type='submit' name='submit' value='Submit'>
    </form> 
</body> 
</html>

 [/code]
   <p> This is sample for PHP </p>
  [code]
  <?php
      echo "Hi, This is PHP";
  ?
  [/code]
  ";

   $code = mysql_real_escape_string($code);
   mysql_query("INSERT INTO tutorials SET tutorial='$code'");

为了显示我正在从数据库中检索内容并使用htmlspecialchars

代码语言:javascript
复制
   echo htmlspecialchars($code);

为了突出显示代码,我使用了google-code-prettify,它要求代码位于带有prettyprint类的pre标记之间。

代码语言:javascript
复制
    <pre class='prettyprint'>
    echo htmlspecialchars($code);
</pre>

无论何时标签,[code][/code]都被<pre class='prettyprint'>";</pre>所取代,

代码语言:javascript
复制
 $code = str_replace("[code]", "<pre class='prettyprint'>", $code);
 $code = str_replace("[/code]", "</pre>", $code);

当我回声时,

代码语言:javascript
复制
echo htmlspecialchars($code);

仅显示纯文本,如:

代码语言:javascript
复制
 <html> <head> <title>This is sample descriptions</title> </head> <body> <form      method='post' action='index.php'> <input type='text' name='username' value=''> <input type='password' name='password' value=''> <input type='submit' name='submit' value='Submit'> </form> </body> </html> </pre> <h5> 2. This is sample code for paragraph </h5> <pre class='prettyprint'> <html> <head> <title>This is sample
EN

回答 2

Stack Overflow用户

发布于 2014-08-24 05:46:23

您在之后调用htmlspecialchars 进行替换,这样<pre>标记也会被转义(并且不会呈现为HTML)。颠倒顺序应该可以做到这一点:

代码语言:javascript
复制
$code = htmlspecialchars($code);
$code = str_replace("[code]", "<pre class='prettyprint'>", $code);
$code = str_replace("[/code]", "</pre>", $code);
echo $code;

此外,还可以查看用于突出显示源代码的highlight_string

票数 1
EN

Stack Overflow用户

发布于 2013-08-23 22:03:22

在您的代码中也有<pre class='prettyprint'></pre>语句。这可能会使代码无法按预期工作。

您可以尝试将代码中的<>分别更改为&lt;&gt;

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18404476

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档