A web developer's blog. PHP, MySQL, CakePHP, Zend Framework, Wordpress, Code Igniter, Django, Python, CSS, Javascript, jQuery, Knockout.js, and other web development topics.

Useful PHP Regular Expressions: For usernames, emails, ip address and more

Here are eight examples of practical PHP regular expressions and techniques that I’ve used over the past few years using Perl Compatible Regular Expressions. This guide goes over the eight different validation techniques and describes briefly how they work. Usernames, telephone numbers, email addresses, and more.

Username Validation – Something often overlooked, but simple to write with regex 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.

    $string = "userNaME4234432_";
    if (preg_match('/^[a-zd_]{4,28}$/i', $string)) {
    echo "example 1 successful.";

Email Addresses – Another practical example would be an email address. This is fairly straightforward to do. There are three basic portions of an email address, the username, the @ symbol, and the domain name. The following example will check that the email address is in the valid form. We’ll assume a more complicated form of email address, to make sure that it works well with even longer email addresses.

    $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.";

IP Addresses – Without pinging or making sure it’s actually real, we can make sure that it’s in the right form. We’ll be expecting a normally formed IP address, such as

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

Get the full article here.

This entry was posted in General and tagged . Bookmark the permalink.

One Response to Useful PHP Regular Expressions: For usernames, emails, ip address and more

  1. anushree says:

    hello this site is amazing

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>