使用代码高亮器显示代码

4

我希望能在教程网站中插入一些编程代码,并附上描述。

以下是HTML代码示例:

 $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,如下所示:
   echo htmlspecialchars($code);

为了突出显示代码,我使用google-code-prettify,它要求将代码置于pre标签内,并添加prettyprint类。
    <pre class='prettyprint'>
    echo htmlspecialchars($code);
</pre>

无论标记出现在何处,将[code][/code]替换为<pre class='prettyprint'></pre>,如下:

 $code = str_replace("[code]", "<pre class='prettyprint'>", $code);
 $code = str_replace("[/code]", "</pre>", $code);

当我使用echo命令时,
echo htmlspecialchars($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> </pre> <h5> 2. This is sample code for paragraph </h5> <pre class='prettyprint'> <html> <head> <title>This is sample

@YaMo 代码没有进行美化,而是显示了纯文本,如下所示:<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. 这是段落的示例代码。 - Code
你在终止 [code] 标签之前,不应该先终止你的 pre 标签吗? - Evan Parsons
2个回答

1
你在替换文本之后调用了htmlspecialchars,导致<pre>标签也被转义并且无法呈现为HTML。将顺序反过来即可解决问题:
$code = htmlspecialchars($code);
$code = str_replace("[code]", "<pre class='prettyprint'>", $code);
$code = str_replace("[/code]", "</pre>", $code);
echo $code;

此外,可以查看highlight_string来突出显示源代码。

0

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接