Making a Drupal Input Format Filter

In my old homebrew blogging system, I built in a function that let me enter references to articles in the Rukapedia but just surrounding an entry’s title in double square brackets: when the post was displayed to the public, the link would automagically get rewritten to become an HTML hyperlink. 

I didn’t want to have to go back and edit these posts and manually insert HTML links for Drupal, so I solved the problem by leaving this as they were and writing a simple Drupal Input Format filter called wikilinks.  It turned out to be really easy to do this.  Here’s how.

First, I created a new directory under the sites/all/modules directory in my Drupal installation called wikilinks.  Inside that directory I created two files: and wikilinks.module.

In I put the following information describing the module:

name = Wiki Links Filter
description = A filter to convert wiki links into HTML links to the wiki.
core = 6.x

 In wikilinks.module I put the following PHP code:

// $Id$

function wikilinks_filter($op, $delta = 0, $format = -1, $text = '', $cache_id = 0) {
  switch ($op) {
    case 'list':
      return array(0 => t('Wiki links'));

    case 'description':
      return t('Converts old-style wiki links to HTML hrefs to');

    case 'prepare':
      return $text;

    case "process":
      $text = preg_replace("/\[\[(.*?)\]\]/","<a href=\"$1\">$1</a>",$text);
      $text = str_replace("","",$text);
      return $text;

      return $text;

The heavy lifting is done in this line:

$text = preg_replace("/\[\[(.*?)\]\]/","<a href=\"$1\">$1</a>",$text);

The text that gets passed to the filter gets scanned and all instances of two square brackets followed by any number of characters followed by another two square brackes gets replaced by a hyperlink to followed by the term that was surrounded.

Once these two files were in place, I just visited Administer > Site Building > Modules, added the Wiki Links module, and then Administer > Site Configuration > Input Formats and clicked the Configure links for the “Full HTML” input format and checked the box beside “Wiki Links.”

Once all this was in place, all the old-style encoded links to the Rukapedia worked fine, with no conversion needed.


Peter Rukavina's picture
Peter Rukavina on July 21, 2009 - 20:44

I forgot the Golden Rule of Drupal: somebody else has always written a module for what you want to do.

oliver's picture
oliver on July 25, 2009 - 15:20

I tried this hack on a piece of halibut and didn’t like the result at all.

Add new comment