10 November, 2010

Regular expression examples in php

Regular expressions in php are a good way for validating against user inputs. Though
usage of regular expressions slow the execution, and are really slower as compared to
string functions, they can be quite fun to play with if known how to. Regex can be used in different programming languages but since i work with PHP, i use them using PHP.

At the beginning, regex seemed to be invincible to me, but as i got into details of
its usage and worked with test codes, i got more and more interested.
So here are some of the common validation examples that can be done using regular expressions in php.
Following mentioned are code for 5 simple regular expression examples for validation in php.

1: Regular expression to check for integer value excluding 0

$test = "123";
$result = 0;

$pattern = "(^([1-9]{1})(([0-9]{1,10}))?)$";
$result = (int) ereg($pattern, $test);
echo $result;

2: Regular expression to check for integer value including 0

$test = "1230";
$result = 0;
$pattern = "(^([0-9]{1})(([0-9]{1,10}))?)$";
$result = (int) ereg($pattern, $test);
echo $result;

3: Regular expression to check for integer value double or float, such as 1.23, 0.48, , 0.487 etc

$test = "123.23";
$result = 0;
$pattern = "^(([0-9]{1,9})(\\.)?)(([0-9]{0,1})([0-9]{0,1})(([0-9]{0,1})([0-9]{0,1})?))$";
$result = (int) ereg($pattern, $test);
echo $result;

4: Regular expression to check for string between 1 to 255 characters, no spaces
 
$test = "thisisatest";
$result = 0;
$pattern = "^([[:alnum:]]){1,255}$";
$result = ( ereg($pattern, $test);
echo $result;

5: Regular expression to check for valid email address
 
$test = "this@gmail.com";
$result = 0;
$pattern = '^[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+' . '@' . '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+\.' . '[-!#$%&\'*+\\./0-9=?A-Z^_`a-z{|}~]+$';
$result = (int) ereg($pattern, $test);
echo $result;

Above mentioned are just few examples that i have mentioned in this post. There is a long way to go with regular expressions in php. I hope this post provide at least some info regarding usage of regular expressions with php.

No comments: