PHP Regular Expressions

Regular Expressions:

In PHP, regular expressions are a pattern that is used to match various text string.

For effective & efficient text processing and manipulation, regular expressions are one of the most powerful tools. For example, it can be used to check the format of data in a phone number, email, name, etc.

The regular expression can be used while creating custom HTML templates that identifies the template tag and replace it with original data.

The syntax for regular expression function is as follow

<?php
	function_name(‘/pattern/’, modifier);
?>

Here,

function_name is the name of the regular functions.

/…./  denote the beginning and end of regular expression.

/pattern/ is the pattern that needed to match.

Modifier is the text string to be matched against.

PHP has built in pattern matching functions that allow us to work with regular functions.

preg_match():

This function searches string for the pattern match. It will return true, if pattern matches else it will return false.

Example:-

<?php
	$text = "Bill Gates owns Microsoft";
	if(preg_match("/owns/", $text)){
			echo "Match Found!!"; 
	}
	else{
			echo "No Match Found!!";
	}
?>

Output:-

Match Found!!

preg_replace():

This function performs the pattern search and replaces the pattern.

Example:-

<?php
	$num = "Copyright 2000";
	$num = preg_replace("([0-9]+)", "2012", $num);
	echo $num; 
?>

Output:-

Copyright 2012

preg_split():

This function splits up the given string into substrings. After splitting up the string it will return array of string.

Example:-

<?php
	$text = "Bill Gates founded Microsoft in 1975";
	$split_text = preg_split("/ /", $text);
	print_r($split_text)
?>

Output:-

Array([0] => Bill[1] => Gates[2] => founded[3] => Microsoft[4] => in[5] => 1975)

Meta Characters:

In PHP, to validate the user input whether it is in pre-defined format or not, we use symbol known as metacharacters.

MetacharacterDescription
$Match the particular string that ends with specified pattern.
^Match particular string that starts with specified pattern.
.Match any single character except new line character.
|It works like logically OR operator.
[ ]To define set of acceptable characters.
+Match one or more occurrence of preceding character.
*Match zero or more occurrence of preceding character.
?Match zero or one occurrence of preceding character.
a-zMatches the lower case letters.
A-ZMatches the upper case letters.
0-9Matches any number from 0 to 9.

Example:-

<?php
	$mob = "9876543210";
	if(preg_match("/^[0-9]{10}$/", $mob)){
			echo "$mob is a valid mobile number";
	}
	else{
			echo "$mob is not a valid mobile number";
	}
?>

Output:-

9876543210 is a valid mobile number