H3XED

How To Create Code Blocks In PHP For Your Blog

Sep 16, 2010   Programming   Nick Vogt   Comments
Please note that this post is over a year old and may contain outdated information.
Having a code block allows you to display code without it being interpreted as HTML. Code blocks are used extensively on programming-related forums and websites so users can show other users the code they use, like this:

<html>
  <body>
    Hello world
  </body>
<html>

The HTML tags inside the above code block were converted to special characters by PHP htmlspecialchars, so that they are not interpreted as normal HTML.


How To Do It


To do this in your blog, first you must surround the bits of code in your post that you want displayed with <pre> tags. Pre stands for preformatted text, and causes the text inside to be displayed in a monospace font, exactly as typed (whitespaces are displayed as typed):

<html>
  <body>
    Here is some code I wrote:
    <pre>echo 'Hello world!';</pre>
  </body>
<html>

Now use PHP to find the <pre> tags and convert all HTML tags inside to special characters. The below format function does just that:

function format($body) {
    $blocks = explode('<pre>', $body);
    for ($i = 1; $i < count($blocks); $i ++) {
        $sections = explode('</pre>', $blocks[$i]);
        $sections[0] = '<pre>' . htmlspecialchars($sections[0]) . '</pre>';
        $blocks[$i] = implode('', $sections);
    }
    $body = implode('', $blocks);
}
Share This Post
Twitter

Comments (0)

Share This Post
Twitter
H3XED © Nick Vogt   RSS   Policies   Twitter