Dynamic Encoding of Ampersands

As you know, I recently converted a number of my archives so that they would use dynamic publishing. Today, I continued the push by converting daily archives and also category feeds to dynamic publishing. Thus far, they seem to be working pretty well, and I’ve been able to clean up my web site considerably.

Along the way, however, I ran into a small problem in that I make use of the excellent Amputator plugin to relieve myself of the erroneous ampersand. The only problem is that it doesn’t work with dynamic publishing. So off to Google I went.

I found my way to Shaun Inman’s page on the subject of using the Amputator regular expression in PHP. This seemed to be perfect, I just needed to put it all together and figure out how the heck to make a PHP plugin. Back to the Six Apart Dynamic Publishing API (and looking through a bunch of the existing code).

In the end, it wasn’t bad at all. First, create a file that contains this code:

  <?php
  function smarty_modifier_encode_ampersands($text) {
   return preg_replace("/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w{1,8});)/i","&amp;",$text);
  }
  ?>

Save the file with a name of modifier.encode_ampersands.php in the plugins directory under the php directory in your main Movable Type directory.

In other words:

  MT_DIR/php/plugins/modifier.encode_ampersands.php

Then just use this as a global filter in your tags, as you would with the static publishing version:

  <$MTEntryBody encode_ampersands="1"$>

And you’re set. The dynamic pages will now take care of encoding those nasty ampersands for you, all without having to lift a finger. Sweet. Special thanks to Shaun Inman for the PHP version and Nat Irons for the original Perl version of the code.


Posted

in