Removing unwanted colons from form field titles

I just created the first poll on my web site and was annoyed by having a colon appear after the question mark in the block title, like this:

Notice the annoying colon right after the question mark.

I remembered that Jeff Robins at Lullabot published an article about how to prevent this problem, but his solution involved copying and modifying the entire theme_form_element function.

In Drupal as with Perl, there is always more than one way to do it. My solution also overrides theme_form_element(), but is far simpler:

function phptemplate_form_element() {
  $args = func_get_args();
  return preg_replace('@([.!?]):\s*(</label>)@i', '$1$2',
      call_user_func_array('theme_form_element', $args));
}

It uses a regular expression to find and remove any colon preceeded by punctuation and followed only by whitespace before the </label>. By using func_get_args() and call_user_func_array(), it also avoids having to know anything about the argument list for theme_form_element(). This code should work for both Drupal 4.7 and 5, though I've only tested it with 5.

Update on June 27, 2007

The above code snippet does not work for required form elements using Drupal 5's default theme because the requiredness-indicator appears in an extra <span> tag between the colon and the </label>. Here is a revised version that works in both cases:

function phptemplate_form_element() {
  $args = func_get_args();
  return preg_replace('@([.!?]):\s*(<span.*?>.*?</span>)?\s*(</label>)@i', '$1$2$3',
      call_user_func_array('theme_form_element', $args));
}