Regular Expressions

Here we will show you some useful regular expression that we use on a daily basis.

PHP regex

Email address validation

This code snippet makes sure that there is a ”@” symbol then some text and then a ”.” followed by no less or more than 2-4 characters.

$validstring = '^([._a-z0-9-]+[._a-z0-9-]*)@(([a-z0-9-]+\.)*([a-z0-9-]+)(\.[a-z]{2,4}))$';
	if (!eregi($validstring,$email)&&$email) {
		$emailcorrect = 0;
	} else  {
		$emailcorrect = 1;
	}
 
	if ($emailcorrect == 0) $errors .= "You must enter a valid Email Address.\n";

Break apart a timestamp

This takes a timestamp from DATETIME and divides each section into a variable to be used seperately later.

$pattern = '/^(\d{1,4})-(\d{1,2})-(\d{1,2})\s(\d*):(\d{2}):(\d{2})$/';
 
$article_year = preg_replace($pattern,'$1' , $article_rs['date_created']);
$article_month = preg_replace($pattern,'$2' , $article_rs['date_created']);
$article_day = preg_replace($pattern,'$3' , $article_rs['date_created']);