View Single Post
Old 12-04-2007, 09:45 PM   #1 (permalink)
Matt83
The Contributor
Upcoming Programmer 
 
Matt83's Avatar
 
Join Date: Oct 2007
Location: Argentina
Posts: 72
Thanks: 18
Matt83 is on a distinguished road
Asterix 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
__________________
http://www.mattvarone.com

Last edited by Matt83 : 12-05-2007 at 12:09 AM.
Matt83 is offline  
Reply With Quote
The Following 19 Users Say Thank You to Matt83 For This Useful Post:
Andrew (12-16-2007), bedri (05-22-2008), codefreek (07-15-2008), danielneri (01-26-2008), drewbee (06-27-2008), hello-world (03-02-2009), iflashlord (04-23-2009), Kalle (02-10-2008), Karl (12-04-2007), nefus (03-19-2009), Nor (12-05-2007), nullbyte (03-19-2008), obolus (01-06-2008), Orc (12-12-2008), ReSpawN (10-10-2008), Salathe (12-05-2007), sketchMedia (05-31-2008), Tanax (12-05-2007), Village Idiot (12-05-2007)