Wednesday, March 3, 2010

8 Practical PHP Regular Expressions

For all us security paranoids Here are eight practical PHP regular expressions i found on the web which came very handy to me:


Quote:
Note: Scroll down to get the latest/correct versions of these Regular expressions
Validating a Username:

Quote:
Something often overlooked, but simple to do with a regular expression would be username validation. For example, we may want our usernames to be between 4 and 28 characters in length, alpha-numeric, and allow underscores.
PHP Code:
$string "userNaME4234432_";
if (
preg_match('/^[a-z\d_]{4,28}$/i'$string)) {
echo 
"example 1 successful.";
Telephone Numbers:

Quote:
Number in the following form: (###) ###-####
PHP Code:
$string "(232) 555-5555";
if (
preg_match('/^(\(?[0-9]{3,3}\)?|[0-9]{3,3}[-. ]?)[ ][0-9]{3,3}[-. ]?[0-9]{4,4}$/'$string)) {
echo 
"example 2 successful.";
Emails:

PHP Code:
$string "first.last@domain.co.uk";
if (
preg_match('/^[^0-9][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[@][a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)*[.][a-zA-Z]{2,4}$/',$string)) {
echo 
"example 3 successful.";
Postal Codes:

PHP Code:
$string "55324-4324";
if (
preg_match('/^[0-9]{5,5}([- ]?[0-9]{4,4})?$/'$string)) {
echo 
"example 4 successful.";
Ip Address:

PHP Code:
$string "255.255.255.0";
if (
preg_match('^(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)(?:[.](?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)){3}$',$string)) {
echo 
"example 5 successful.";
Hexadecimal Colors:

PHP Code:
$string "#666666";
if (
preg_match('/^#(?:(?:[a-f\d]{3}){1,2})$/i'$string)) {
echo 
"example 6 successful.";
Multi-line Comments:

PHP Code:
$string "/* commmmment */";
if (
preg_match('/^[(/*)+.+(*/)]$/'$string)) {
echo 
"example 7 successful.";
Dates:

Quote:
MM/DD/YYYY format
PHP Code:
$string "10/15/2007";
if (
preg_match('/^\d{1,2}\/\d{1,2}\/\d{4}$/'$string)) {
echo 
"example 8 successful.";
Some might be more/less useful than the others but that will depend on the project you are working on.

Hope you find them useful too. Source/credits: Devolio.org

No comments:

Post a Comment