rss feed Twitter Page Facebook Page Github Page Stack Over Flow Page

PHP Regular Expression

Regular expressions are a very powerful when you want to validate user inputs. They can find any kind of words or characters and identify errors very accurately. Although, because they are very worthy, they are sometimes quite hard to use.

Here's some quick basics about regular expressions:

Operators

Pattern Modifiers

Regular Expression Matches

Let's see some examples:


define('REGEX_EMAIL', '/^[^\W][a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)*\@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z]{2,6}$/');
define('REGEX_DOMAIN', '/^(([a-zA-Z0-9-]+)\.?)([a-zA-Z0-9-]+)\.(([a-zA-Z]{2,6})|([a-zA-Z]{2,3}\.[a-zA-Z]{2}))$/');

function isEmail($e) {
  return (bool)preg_match(REGEX_EMAIL, $e);
}

function isDomain($d) {
  return (bool)preg_match(REGEX_DOMAIN, $d);
}

function highlightWords($str, $word) {
  return preg_replace('/\b(' . $word . ')\b/i', '<span class="bold">\1</span>', $str);
}

function validateAlpha($str) {
  return (bool)preg_match('/^[A-Za-z0-9_\-\ ]+$/', $str);
}

// Valid Email:
var_dump(isEmail('john.doe@domain.tld')); // will output: bool(true)
var_dump(isEmail('john_doe@do.main.tld')); // will output: bool(true)
var_dump(isEmail('john-doe@do-main.tld')); // will output: bool(true)
var_dump(isEmail('john@doe.main.tld')); // will output: bool(true)

// Invalid Email:
var_dump(isEmail('john@doe')); // will output: bool(false)

// Domain
var_dump(isDomain('domain.com')); // will output: bool(true)
var_dump(isDomain('sub.domain.com')); // will output: bool(true)
var_dump(isDomain('domain.co.uk')); // will output: bool(true)
var_dump(isDomain('www.domain.co.uk')); // will output: bool(true)

// Invalid Domain:
var_dump(isEmail('johndoe.')); // will output: bool(false)

// HighLight words
echo highlightWords('Hi John, How are you?', 'John'); // will output: Hi <span class="bold">John</span>, How are you?

// Validate letters, numbers
var_dump(validateAlpha('abc123')); // will output: bool(true)
var_dump(validateAlpha('0a.8@')); // will output: bool(false)