Learn about regular expressions in PHP.

We'll cover the following

We often use HTML forms to collect data or inputs from users. Our role as developers is to make sure that the submitted data is valid. Imagine a form where users are allowed to submit a name in the email field. With such a form, we wouldn’t be able to contact the user.

Should we trust the user and assume that they’ll never make a mistake in our forms? forms? Because humans are fallible, the wise approach would be to not work with that assumption.

As the adage says:

“Never ever trust user inputs.”

We must always check whether the submitted data meets our expectations.

The goal of this section is to explore the different techniques for validating form inputs. More precisely, we’ll be learning about:

  • Regular expressions, also known as Regex.
  • Client-side validation with HTML5.
  • Client-side validation with JavaScript.
  • Server-side validation with PHP.

Without further ado, let’s learn how Regex is used for validating form inputs.


The use of Regex or regular expression for data validation is many. We won’t be able to cover them all in this small lesson, but we’ll still cover some of its most important concepts.

A Regex or regular expression is a sequence of characters that represent a pattern. It is also the “language” that we use to specify our program patterns so that the computer can recognize them.

Let’s look at a simple example of a regular expression.

Given the sentence below:

“I teach at Educative.”

If we want to check whether the sentence contains the word “Educative”, we’ll write a pattern like this: /Educative/. We’ll then test this pattern and the sentence in the widget below to see the result.

Note that a pattern should always be wrapped by delimiters. These delimiters can be any sign we choose, such as “/” or “#”.

The general syntax for a pattern is /pattern/options. An option or a flag can be used for the instance “i” to ignore the case.

Let’s learn about some common patterns that we may come across.


Pattern Description
| OR matches the first, second, or third word, and so on.
. Matches only a single character.
^ A string start anchor matches the word only if it’s at the beginning.
$ A string end anchor matches the word only if it’s located at the end.


Get hands-on with 1000+ tech skills courses.