Zend Framework 1 has some excellent filters for making sure the input from a form is what you want. That said there are going to be times when creating your own filter is a must, this happened to me the other day as we needed a way to reformat UK postcodes and make sure we had a standard format in the database. Criteria for postcodes was:

  • all letters to be uppercase
  • all whitespace be removed
  • space inserted between the out code and the in code parts

With the criteria down we can set to in writing our filter, this is not as difficult as it may sound as all we do is write a class which implements the Zend_Filter_Interface like:

class App_Filter_Postcode implements Zend_Filter_Interface
{

}

So to make our filter useful we have to add at least one method which is defined by the filter interface, this is called ‘filter’ and we will add all our code in this method and return the result like so:

class App_Filter_Postcode implements Zend_Filter_Interface
{
    /**
     * Defined by Zend_Filter_Interface.
     *
     * @param string $value
     * @return string
     */
    public function filter($value)
    {
        // make it upper case
        $new = strtoupper($value);

        // remove all spaces
        $new = str_replace(' ', '', $new);

       // get the last 3 characters and add a space before them.
       $replace = substr($new, -3, 3);
       $new = str_replace($replace, ' ' . $replace, $new);

       return $new;
    }
}