Display code using code highlighting

I want to embed some code along with descriptions like a tutorial site.

This is 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 retrieve the content from the database and using htmlspecialchars like,

  echo htmlspecialchars($code); 

To highlight the codes, I use google-code-prettify , which requires the code to be between the pre tag with the prettyprint class,

  <pre class='prettyprint'> echo htmlspecialchars($code); </pre> 

Wherever the [code] and [/code] tags 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:

  <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 
+4
source share
2 answers

You call htmlspecialchars after executing the replacements, so the <pre> tags are also escaped (and will not display as HTML). The reverse order should do the trick:

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

Also, see highlight_string to highlight the source code.

+1
source

The code also contains instructions <pre class='prettyprint'> and </pre> . This can lead to code not working properly.

You can try changing < and > in your code to &lt; and &gt; respectively.

0
source

Source: https://habr.com/ru/post/1498607/


All Articles