Home > PHP > A few useful regular expressions

A few useful regular expressions

January 16th, 2009 Leave a comment Go to comments

Here are a few useful regular expressions I’ve collected. I will append regular expressions to this list whenever I find a useful new one.
If you run windows, check out http://www.weitz.de/regex-coach/. It’s a very useful application to write and test regular expressions. If you know a good linux variant of this program, please comment on this article.

E-mail:
 ^[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*\.[a-z]{2,4}$

IP address:
^(?:(?:25[0-5]|2[0-4]\d|[01]\d\d|\d?\d)(?(?=\.?\d)\.)){4}$

MySQL timestamp (leap year from 1901 to 2099):
^((\d{2}(([02468][048])|([13579][26]))[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|([1-2][0-9])))))|(\d{2}(([02468][1235679])|([13579][01345789]))[\-\/\s]?((((0?[13578])|(1[02]))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\-\/\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\-\/\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\s(((0?[1-9])|(1[0-2]))\:([0-5][0-9])((\s)|(\:([0-5][0-9])))))?$

Dutch (local) phone numbers:
((^06((\s{0,1})|(\-{0,1}))[0-9]{8}$)|(^[0-9]{3,4}(\s{0,1}|\-{0,1})[0-9]{6,7}$)|(^\+{1}[0-9]{2}(\s{0,1}|\-{0,1})[0-9]{2,3}(\s{0,1}|\-{0,1})[0-9]{6,7}$)) 

International phone number:
^(\(?\+?[0-9]*\)?)?[0-9_\- \(\)]*$

Dutch zip/postal code (with or without space):
^[0-9]{4}\s{0,1}[a-zA-z]{2}$

  1. No comments yet.
  1. No trackbacks yet.