What is Regex – Regular Expression

In this article, we will take a detailed look at PHP regex with examples, how it works, and its applications.

In computing, a regular expression, which is often abbreviated as “regex“, is a sequence of characters used to define a search pattern.

It is a language that is used to match patterns in text data in order to identify specific patterns.

Regex are a type of expression that is commonly used to manipulate text data, whether it is in programming languages, text editors, or other applications.

There are a number of powerful methods available for manipulating text data, such as searching for specific patterns or substrings, replacing text, and performing other operations on the data.



What is regex in PHP?

PHP regex or regular expression, is a sequence of characters that specify a search pattern.

The PHP regex engine provides a set of functions that allow developers to search for patterns in strings, replace parts of strings, and extract information from strings.

As an example, the use of regular expressions can be used in a number of different ways, such as searching for all occurrences of a specific word in a text document, and extracting all of the email addresses from a list of text data.

There are a number of ways to use regular expressions, but first you need to understand the syntax and structure of PHP in order to use them.

You can use regular expressions to easily manipulate and process large amounts of text, which is valuable for anyone who works with text data.

Syntax

The regular expression in PHP contains delimiters, patterns, and optional modifiers.

$exp = "/mrexamples/i";

The example above uses / as a delimiter, mrexamples as the pattern to search for, and i as the case-insensitive modifier.

There are a number of characters that can be used as a delimiter, but no letter, number, backslash or space can be used.

Usually, the top delimiter is the forward slash (/), but when your pattern contains forward slashes, it may be more suitable to use another leading delimiter such as # or ~.


PHP Regex Functions

There are a number of PHP functions that allow you to use regular expressions, including:

Regex FunctionsOverview
preg_match()searches a string for a pattern and returns the first match.
preg_match_all()searches a string for all matches of a pattern and returns an array.
preg_replace()replaces a pattern in a string with a specified replacement.
preg_split()splits a string into an array based on a specified pattern.
These functions provide a powerful set of tools for working with regular expressions in PHP.

PHP Regex preg_match()

Preg_match() is a built-in function in PHP that is used to do regular expression matching by comparing the contents of a regular expression with the string. An expression is evaluated by searching a string for a pattern that matches a regex and returning the first match found in the string.

There are three parameters that are passed to the preg_match() function:

  • Firstly, we need to specify the regular expression that should be matched.
  • Secondly, we need to provide a string to be searched for as the second parameter.
  • Thirdly, there is an optional variable that will be filled with matches found in the second step of this algorithm.

When a match is found, preg_match() returns 1, and this information is stored in the third parameter if a match was found.

When preg_match() does not find any matches, it returns 0 as a result.

Below is an example of using a regular expression to look for “mrexamples” in a string in a case-insensitive manner:

Example: 

<?php $string = "Visit mrexamples for learning programming languages"; $pattern = "/mrexamples/i"; echo preg_match($pattern, $string); // Outputs 1 ?>
This is the another example of using preg_match() function to look for “PHP” in a string in a case-insensitive manner:

Example: 

<?php $string = "PHP is fun"; $pattern = "/PHP/i"; echo preg_match($pattern, $string); // Outputs 1 ?>

PHP Regex preg_match_all()

This preg_match_all() function is a built-in PHP function that can be used for the purpose of matching a regular expression across a whole range of expressions in a document.

Similar in nature to preg_match(), it returns a list of all matches found within a string, instead of just returning the first match found in the string, like preg_match().

There are three parameters that are passed to the preg_match_all() function:

  • Firstly, we need to specify the regular expression that should be matched.
  • Secondly, we need to provide a string to be searched for as the second parameter.
  • Thirdly, there is an optional variable that will be filled with matches found in the second step of this algorithm.

The preg_match_all() function returns a count of matches if a match is found, and stores that number in parameter 3 if a match is found. A value of 0 is returned by preg_match_all() if no matches are found.

Here is an example of how a regular expression can be used to do a case-insensitive count of how many occurrences of the word “ain” there are in a string using a regular expression:

Example: 

<?php $string = "Peter Piper Picked a Peck of Pickled Peppers."; $pattern = "/pe/i"; echo preg_match_all($pattern, $string); // Outputs 5 ?>
The following example will help you gain a better understanding of the preg_match_all() function:

Example: 

<?php $string = "The price of the product is €10.99"; // The string to search $pattern = "/pr+/"; // A regular expression to match any sequence of digits echo preg_match_all($pattern, $string); // Outputs 2 ?>

PHP Regex preg_replace()

Preg_replace() is a built-in PHP function that searches and replaces regex patterns within strings.
There are three parameters that are passed to the preg_replace() function:
  • As the first parameter, we need to specify the regular expression pattern that we want to match.
  • Second, we have the replacement string, which is the second parameter.
  • In the third parameter, you can provide a string that you would like to search for.
If a matching pattern is found, then preg_replace() will replace the matched string with the replacement string, and will return the modified string if a match was found.
Preg_replace() will return the original string in the case that a match cannot be found.
Example of replacing Microsoft with mrexamples using a case-insensitive regular expression:

Example: 

<?php $string = "Visit Microsoft!"; $pattern = "/microsoft/i"; echo preg_replace($pattern, "mrexamples", $string); // Outputs "Visit mrexamples!" ?>

PHP Regex examples

The following example will help you gain a better understanding of the preg_replace() function:

Example: 

<?php $string = "The price of the product is €10.99"; // The string to search $pattern = "/10.99/"; // A regular expression to match any sequence of digits echo preg_replace($pattern, 12.99, $string); // Outputs 2 ?>

Example Explanation

In above example, the preg_replace() function is used to search the string ‘The price of the product is $10.99’ for a regular expression pattern /10.99/ and replace it with the value 12.99.

The regular expression pattern /10.99/ matches the string ‘10.99’ in the original string, which represents a price of $10.99.

The preg_replace() function replaces this matched string with 12.99, resulting in the modified string ‘The price of the product is $12.99’.

The modified string is then outputted using the echo statement, resulting in the output: The price of the product is $12.99.


PHP Regex preg_split()

preg_split() function performs a regular expression pattern match on a string and splits the string into an array based on the pattern match.

This function takes two parameters:

  • The first is the regular expression pattern to match.
  • Second is the input string to split. It returns an array of substrings from the input string that were separated by the matched pattern.

Here is an example of using preg_split() to split a string based on a regular expression pattern:

Example: 

<?php $string = 'mrexample'; $result = preg_split('//', $string , -1, PREG_SPLIT_NO_EMPTY); print_r ($result); ?>

PHP Regex Modifiers

Searches can be modified by adding modifiers to them in order to change how they behave.

ModifierOverview
iProvides a search that is case-insensitive.
mUsing the multiline search function, you can find out if a pattern matches the beginning or end of a string. This means that you’ll match the beginning and end of each line.
uEnsures that patterns encoded in UTF-8 are correctly matched.

PHP Regex Patterns

There are a few different ways of finding a range of characters using brackets:

PatternsOverview
[abc]Between the brackets, choose one character.
[^abc]Choose any character but not between the brackets.
[0-9]Find one character between 0 and 9.

PHP Regex Metacharacters

Metacharacters are characters that have a special meaning associated with them:

MetacharactersOverview
|The patterns are separated by | so that you can find an exact match for any of them, for example: cat|dog|fish
.Search for just one instance
^You can use this method to find a match at the beginning of a string, such as: ^Hello
$This method finds a match at the end of the string, as in the following example: World$
\dThis method finds a digit.
\sWhitespace characters are found using this method
\bYou can search for a match by looking at the beginning of the word like this: /bWORD, or by looking at the end of the word like this: WORD\b
\uxxxxBy using this method, it is possible to find the Unicode character that is associated with the hexadecimal number xxxx

PHP Regex Quantifiers

In order to define quantities, we use quantifiers:

QuantifiersOverview
n+Strings containing at least one n are matched.
n*Strings containing zero or more occurrences of n are matched.
n?Strings containing zero or one occurrence of n are matched.
n{x}Strings containing a sequence of X n’s are matched.
n{x,y}Strings containing a sequence of X to Y n’s are matched.
n{x,}Strings containing a sequence of at least X n’s are matched.
Remember: The backslash ( \ ) can be used to escape one or more of the special characters if your expression needs to search for one of them.

For example, you can use the following expression to search for one or more question marks:

$pattern = ‘/?+/’;

PHP Regex Grouping

Quantifiers can be applied to entire patterns using parentheses. Also, they can be used in order to select portions of the pattern to use as a match, rather than the entire pattern.

For example, you can use grouping to find the word “banana” by looking for “ba” followed by “na” on two different times:

Example: 

<?php $string = "Bananas and grapes."; $pattern = "/ba(na){2}/i"; echo preg_match($pattern, $string); // Outputs 1 ?>

In the example below, we are grouping “PHP” by followed by the occurrence of “PHP” in $title:

Example: 

<?php $pattern = '/\w*PHP/'; $title = 'CakePHP & FuelPHP are PHP Frameworks';if (preg_match_all($pattern, $title, $matches)) { print_r($matches[0]); } ?>
We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *