我想插入一些编程代码和描述,就像教程网站一样。
这是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 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
您在执行替换操作之后调用htmlspecialchars
,因此<pre>
标记也会转义(不会呈现为HTML)。反转订单应该会奏效:
$code = htmlspecialchars($code);
$code = str_replace("[code]", "<pre class='prettyprint'>", $code);
$code = str_replace("[/code]", "</pre>", $code);
echo $code;
此外,请查看highlight_string以突出显示源代码。
代码中也有<pre class='prettyprint'>
和</pre>
语句。这可能会使代码无法按预期工作。
您可以尝试将代码中的<
和>
分别更改为<
和>
。