Format Code Inside PRE Tags within TextMate Using PHP

By  on  

Creating blog posts has been greatly sped up by the use of TextMate. I've created a bunch of blog formatting commands to do various operations on posts including adding paragraph tags, formatting headings, and generating content based on string templates. One of my favorites is a PHP function that html-entitizes (your word of the day) code with PRE tags.

The PHP

function replace_angles($matches) {
return str_replace($matches[1],htmlentities($matches[1]),$matches[0]);
}
$file = file_get_contents('php://stdin');
$file = preg_replace_callback('/<pre.*?>(.*?)<\/pre>/imsu',replace_angles, $file);
echo $file;

The first step is reading in the buffer's contents. The next step is using PHP to extract the PRE code and replace it with htmlentities(code). Mission accomplished! I use this frequently within my blog -- maybe you can too.

Recent Features

  • By
    Conquering Impostor Syndrome

    Two years ago I documented my struggles with Imposter Syndrome and the response was immense.  I received messages of support and commiseration from new web developers, veteran engineers, and even persons of all experience levels in other professions.  I've even caught myself reading the post...

  • By
    Write Better JavaScript with Promises

    You've probably heard the talk around the water cooler about how promises are the future. All of the cool kids are using them, but you don't see what makes them so special. Can't you just use a callback? What's the big deal? In this article, we'll...

Incredible Demos

  • By
    Dijit&#8217;s TabContainer Layout:  Easy Tabbed Content

    One of Dojo's major advantages over other JavaScript toolkits is its Dijit library.  Dijit is a UI framework comprised of JavaScript widget classes, CSS files, and HTML templates.  One very useful layout class is the TabContainer.  TabContainer allows you to quickly create a tabbed content...

  • By
    Pure CSS Slide Up and Slide Down

    If I can avoid using JavaScript for element animations, I'm incredibly happy and driven to do so.  They're more efficient, don't require a JavaScript framework to manage steps, and they're more elegant.  One effect that is difficult to nail down with pure CSS is sliding up...

Discussion

  1. Have you looked into using markdown in textmate instead? It’s already got a lot of what you’re talking about :D

  2. Dave Demon

    hello Sir,
    I would like to ask u some question. I tried to use htmlentities like that
    htmlentities('hello', ENT_QUOTES);
    but it is not working. (also htmlspecialchars ) I would like to know how to do this problem.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!