Creating a Drupal Module — Part 6: Exposing Functionality and Enforcing Permissions

We are finally ready to implement the filtering code to turn "[testmod datetime]" into the current date and time by calling the PHP function made in part 3. We will use the power of regular expressions to do this succinctly.

I recommend using an online regular expression checker (such as this one) to ensure your regular expression is working as intended. Let's let the user enter either [testmod] or [testmod datetime]. Everything else will be invalid.

  1. // search for [testmod] or [testmod datetime]
  2. preg_match_all( '|\[testmod((\s+)(datetime))?]|', $text, $results );

Be sure to test this rigorously -- it is important to be familiar with how the $results are returned. Results for '[testmod   datetime]' will give:

  1. Array
  2. (
  3. [0] => Array
  4. (
  5. [0] => [testmod datetime]
  6. )
  7. [1] => Array
  8. (
  9. [0] => datetime
  10. )
  11. [2] => Array
  12. (
  13. [0] =>
  14. )
  15. [3] => Array
  16. (
  17. [0] => datetime
  18. )
  19. )

You'll notice that the 'parameter' we are looking for (datetime) is stored in array position [3]. Loop through the $results and replace the given text with the results of our custom function made in part 4.

  1. case 'prepare':
  2. // Intended as a place to escape HTML. Prepare is called
  3. // before process. This will usually be uncessesary.
  4. //
  5. // For more info visit the Drupal API page:
  6. // http://api.drupal.org/api/function/hook_filter/6
  7.  
  8. // search for [testmod] or [testmod datetime]
  9. preg_match_all( '|\[testmod((\s+)(datetime))?]|', $text, $matches );
  10.  
  11. // loop through all matches
  12. // [0] => array with full text of the match(es)
  13. // [1] => array with text of everything after '[testmod'
  14. // [2] => array with text of spaces preceding 'datetime' text
  15. // [3] => array with text of 'datetime'
  16. for ( $i = 0; $i < count($matches[0]); $i++ )
  17. {
  18. // insert current date/time if 'datetime' exists. Otherwise clear it out.
  19. if ( $matches[3][$i] == 'datetime' )
  20. $text = str_replace( $matches[0][$i], testmod_get_datetime(), $text );
  21. else
  22. $text = str_replace( $matches[0][$i], '', $text );
  23. }
  24.  
  25. return $text;

In the body of the loop, we check to see if 'datetime' is passed in. If so, the current date and time replaces the existing text. Otherwise the entire tag is removed by replacing the full text of the match with an empty string.

The method shown is by no means the most efficient way of doing this. It could all be done with a single preg_replace() call. The method shown was for clarity. Additionally, I have left out unnecessary hooks such as _help to simplify things. This tutorial is simply meant as a starting point. For more information, check out the links below.

File Icon Download testmod.zip for the fully functioning example.

Sources, references, and much more information: