Last updated on March 28th, 2016 at 03:28 pm

Regular expression is very important when you need to validate data. But Regular expression is not easy to understand for biginners. In this tut i will explain you how we can create regular expression and also tell some expression which we regular use for form validation.

List of symbols we used in regular expression.

Symbol

Explanation

\Escape Special characters.
.Match a single character of any value, except end of line.
^Match the start of the line.
$Match the end of the line.
|Match either the regular expression preceding it or the regular expression following it.
[ ]Match any single character from within the bracketed.
!Do not match the next character or regular expression.
?Match 0 or 1 time.
*Match 0 or more times.
+Match 1 or more times.

Now we use these symbol and create some basic regular expressions.

Regular Expression to check integer no

preg_match('/^[0-9]*$/', '1234');

Regular Expression to check character value without space

preg_match('/^[a-z]*$/', 'abc');

Regular Expression to check lower and upper case letter

preg_match('/^[a-zA-Z]*$/', 'Aabc');

Regular Expression to check lower and uppercase letter and integer and also white space

preg_match('/^[a-z0-9 ]*$/i', 'trinity Canyon 01');

Expression to validate email address

preg_match("/^[\.A-z0-9_\-\+]+[@][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z]{1,4}$/i", "[email protected]");

you also use php filter_var() function to validate email

filter_var("[email protected]", FILTER_VALIDATE_EMAIL)

Now some other regular expression

\A     Start of string
\z     End of string
\s     Any whitespace character
\S     Any non-whitespace character
\d     Any digit
\D     Any non-digit
\w     Any word character (letter, number, underscore)
\W     Any non-word character
\b     Any word boundary character
(…)     Capture everything enclosed
(a|b)     a or b
a{3}     Exactly 3 of a
a{3,}     3 or more of a
a{3,6}     Between 3 and 6 of a

These are simple and easy example of regular and working expression.

Happy Coading!