The following class is contained within a file called 'regex.php':
class RegEx { /*** USERNAME ***/ public static function username() { return "/^[a-zA-Z0-9](?=[\w\-.]{5,19}$)[\w\-]*\.?[\w\-]*$/i"; } /*** EMAIL basic email checker ***/ public static function email() { return "/^[\w][\w.-]+?(\w@)[\w\-]+\.[A-Za-z]{2,10}(\.[\w]{2,5})?$/"; } /*** DATE FORMAT dd-mm-yyyy where - can also be / or . ***/ public static function dateFormat() { return "~^[0-9]{1,2}[./-][0-9]{1,2}[./-]([0-9]{2}|[0-9]{4})$~"; } /*** CURRENCY FORMAT d+.dd ***/ public static function currencyFormat() { return "/^\d+\.\d{2}$/"; } /*** FULL POSTCODE ***/ public static function postcode() { return "/^(?=[a-z0-9 ]{6,8}$)[a-z]{1,2}\d{1,2}[a-z]? \d[a-z]{2}$/i"; } }
If we find ourselves needing a regular expression we include the file:
if(!class_exists('RegEx')) { include 'path/to/regex.php'; }
Because the function is a static one we do not need to create an instance of the class. So lets say we are checking the username, what we would write is:
if(preg_match(RegEx::username(), $u_name)) { //succeed }
If you need a new expression you simply create a new function of the format shown.
Pretty straightforward really.
No comments:
Post a Comment