Sunday, July 18, 2010

Formater Class with Regular Expressions

Here is a another useful class for formating any type of data, using regular expression.

It has two parts, one var called $formats where we store the REGEX and one funcion called format where we execute it.

class Formater{
  public static $formats=array(
    'date2sql' => array("'^([0-9]{2}).([0-9]{2}).([0-9]{4})'","$3-$2-$1"),
    'sql2date' => array("'^([0-9]{4}).([0-9]{2}).([0-9]{2})'","$3/$2/$1"),
  );

  public static function format($string,$type) {
        if (!isset(self::$formats[$type])) return $string;
        $find = self::$formats[$type][0];
        $replace = self::$formats[$type][1];

        return preg_replace($find,$replace,$string);
   }
}


// Mode of use - Como usar
$date1 = Formater::format('2010-08-01','sql2date'); // returns 01/08/2010
$date2 = Formatter::format('01/08/2010','date2sql'); // returns 2010-08-01

You may use it for anything you need, all you've to do it simply add your regex to the $formats and there you go!

This is the type of class you'll need in every project you do!

No comments:

Post a Comment