Archive
This post is archived and may contain outdated information. It has been set to 'noindex' and should stop showing up in search results.
How To Create Code Blocks In PHP For Your Blog
Sep 16, 2010ProgrammingComments (0)
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);
}
Comments (0)
Add a Comment


Please review the commenting policy prior to commenting.
No comments yet