Using Drupal 7 text filter (input format)

Posted on June 13, 2012


Simple example of how to do your own text filter (formally known as input format) module for Drupal 7. Documentation is not very clear, hence this posting. As starters, you have to create your new module files and directories, for example, myformat/ and so on. Check how to do that from your favourite Drupal guide book.

Once the basics for module are set, add these hooks to myformat.module: myformat_filter_info(), _myformat_filter_prepare() and _myformat_filter_process(). Hooks starting with an underline are not actually hooks, but something else which Drupal does some processing automatically. You can’t work without them, though, and as the documentation is not clear on this at all, we just have to assume that everything is fine. These “sub-hooks” have to be introduced in myformat_filter_info().

Here follows a minimal example of how to write the hooks.


* Implements hook_filter_info().
function myformat_filter_info() {
$filters = array();
$filters[‘myformat’] = array(
‘title’ => t(‘My formatter’),
‘description’ => t(‘My custom modifications’),
‘prepare callback’ => ‘_myformat_filter_prepare’,
‘process callback’ => ‘_myformat_filter_process’,
return $filters;


* Implements filter prepare callback.
function _myformat_filter_prepare($text, $filter, $format, $langcode, $cache, $cache_id) {
return $text;


* Implements filter process callback.
function _myformat_filter_process($text, $filter, $format, $langcode, $cache, $cache_id) {
$text = str_replace(“text_to_change”, “zzz_text_to_change_zzz”, $text);
return $text;

Enable module, add text format to your content via Drupal Configuration and give it a try. If everything is ok, any content written with myformat has now string “text_to_change” changed on fly to “zzz_text_to_change_zzz”. If you have saved text on your page, but nothing shows up when you view it, probably there is an error with module sub-hooks. Remember to have both _filter_prepare and _filter_process defined, both returning something.

This tutorial is useful to have some special effects on certain keywords. For example, you could write the module so that a word Tarzan will always be presented in bold, ie. <strong>Tarzan</strong>, without user having to (or allowed to) pay any attention to this while managing the content. Tag replacement and other more complex features are calling for regex. As the official documentation is lacking, best way to learn more is to download contributed modules and to see how they are made. Here is one good example.