PHP

Regular Expression


 

A regular expression, often abbreviated as regex or regexp, is a concise and flexible sequence of characters that defines a search string pattern. It is a powerful tool used in text processing, enabling you to describe and match complex patterns within strings. 

 

Regular Expression Functions

There are multiple functions that use regular expressions. The preg_match(), preg_replace() and preg_match_all() functions are most used regular expression functions.

 

Function

Use

preg_match()

Performs a regular expression match

preg_replace()

Performs a regular expression search and replace

preg_match_all()

Finds all occurrences of a pattern in a string

 

Preg_match():

The `preg_match()` function in PHP is used for performing regular expression pattern matching on a string. It checks whether a given string matches a specified pattern and return 0(false) or 1(true).

 

Syntax: 

<?php
		preg_match(pattern, subject, matches);
	?>

 

Example:

<?php
		$str = "Hello Learners";
		$search = "/Learners/";
		echo preg_match($str, $search); // 1
	?>

 

Preg_match_all():

The preg_match_all()   function in PHP is used to perform a regular expression match on a string. It finds all occurences of the pattern in the given pattern and stores the result in an array.

 

Syntax:

<?php
		preg_match_all(pattern, match, flags);
	?>

 

Example:

<?php
		$str = “The star lit up the dark sky, sparkling from afar”'
	?>

 

Preg_replace():

In PHP, the `preg_replace()` function is used for performing regular expression search and replace a string with given string.

 

Syntax:

<?php
		preg_replace(pattern, givenStr, str);
	?>

 

Example:

<?php
		$str = "Welcome Developers";
		$pattern = "/developers/i";
		echo preg_replace($pattern, "Coders", $str);
	?>

 

Regular Expression Modifiers

There are various modifiers available, which can be added to the end of a regular expression pattern to modify its behaviour. These modifiers are used to perform case-insensitive matches, multi-line matches, and other variations. Here are some common regular expression modifiers.

 

Some common regular expression modifiers are as follows: 

Modifier

Use

I

Performs case-insensitive search

M

Performs multiple search

u

Matching in Unicode characters(UTF-8)