I want to insert some programming code along with the descriptions like a tutorial site.
This is the sample code for HTML code:
$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'");
To display I am retrieving the content from a database and using htmlspecialchars
like,
echo htmlspecialchars($code);
For highlighting the codes, I am using google-code-prettify
, that requires that the code be in between pre
tag with prettyprint
class,
<pre class='prettyprint'>
echo htmlspecialchars($code);
</pre>
Where ever the tags, [code]
and [/code]
are replaced with <pre class='prettyprint'>";
and </pre>
like,
$code = str_replace("[code]", "<pre class='prettyprint'>", $code);
$code = str_replace("[/code]", "</pre>", $code);
When I echo,
echo htmlspecialchars($code);
only plain text is displayed like:
<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
There are <pre class='prettyprint'>
and </pre>
statements in your code too. This may make the code not work as expected.
You may try by changing <
and >
in your code to <
and >
respectively.
You're calling htmlspecialchars
after doing the replacements so the <pre>
tags are escaped as well (and won't be rendered as HTML). Reversing the order should do the trick:
$code = htmlspecialchars($code);
$code = str_replace("[code]", "<pre class='prettyprint'>", $code);
$code = str_replace("[/code]", "</pre>", $code);
echo $code;
Further, have a look at highlight_string for highlighting source code.