PHP regular Expression | A Quick Start Guide

PHP uses preg_match to work with regular expressions and the syntax is similar to that of . The process of matching regular expression matching is simple.


The preg_match takes two parameters:

preg_match ( pattern, string to be checked against the pattern) 

Suppose you are doing a regular expression check on a user submitted form name “name”, your php regular expression will look like:

preg_match('pattern',  $_POST['name'])

In PHP, all patterns must be entered between inverted quotes and two forward slashes ‘/your pattern here/’. This would be something like this:

preg_match('/pattern/', $_POST['name'])

Again the pattern is represented by ^ symbol to mark the beginning and $ symbol to mark the end of the pattern. So the pattern would look like

preg_match('/^pattern$/', $_POST['name'])

Finally time to add all allowed patterns in the [ ] followed by a + sign

preg_match('/^([A-Z]+)$/', $_POST['name']) // only allows capital letters in the $_POST['name']
preg_match('/^([A-Za-z]+)$/', $_POST['name']) // only allows letters A to Z and a to z in the $_POST['name']
preg_match('/^([A-Za-z0-9]+)$/', $_POST['name']) // only allows letters and numbers 0 to 9 in the $_POST['name']
preg_match('/^([A-Z0-9-~!@#&]+)$/', $_POST['name']) // allows letters, numbers & special characters in the $_POST['name']


When doing a form checking, that allows no special characters, you may not just want to check patterns but would also require to replace or remove unwanted characters. PHP provides preg_replace to do that.

preg_replace accepts 3 parameters

preg_replace('pattern to be checked', 'matching patterns to be replaced by', 'in which string')

so a typical preg_replace might look like:

preg_replace('/[^[@~!#%^&]/', '', $_POST['name']) // this will replace characters @~!#%& with blank "" thus preventing things like SQL injections

Now for some practical example:

if(isset($_POST['submit'])) {
	if(preg_match('/^([_-+]+)$/', $_POST['name'])) {
		echo "Sorry no special characters allowed";