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 255.255.255.0.
$string = "255.255.255.0"; 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.
hello this site is amazing