Table of contents
1.
Introduction
2.
What is Regex in PHP?
3.
Syntax of PHP regex functions
4.
Functions of Regular expression in PHP
4.1.
preg_match() 
4.2.
PHP
4.3.
preg_match_all() 
4.4.
PHP
4.5.
preg_replace()
4.6.
PHP
5.
PHP Regular Expression Modifiers
6.
Grouping in PHP 
6.1.
PHP
7.
Quantifiers in PHP
8.
Advantages of PHP regex Function
9.
Frequently Asked Questions
9.1.
What is an example of a regular expression?
9.2.
How to test regex in PHP?
9.3.
How to validate a regular expression in PHP?
9.4.
How to check if a string matches regex in PHP?
10.
Conclusion
Last Updated: Oct 23, 2024
Easy

PHP Regular Expressions (regex)

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Regular expressions, often abbreviated as regex, are a powerful tool in PHP for pattern matching and string manipulation. They allow developers to search, replace, and validate data with precision, making it easier to handle complex text-processing tasks. In this blog, we will explore the fundamentals of regular expressions in PHP, exploring syntax, common functions, and practical examples to help you harness the full potential of regex for tasks like form validation, data extraction, and more.

Regular Expressions in PHP

What is Regex in PHP?

Regex, or regular expressions, in PHP is a sequence of characters that forms a search pattern. It is used for string matching, searching, and manipulation, allowing developers to validate input, extract data, and perform complex text transformations. PHP provides built-in functions like preg_match(), preg_replace(), and preg_split() to work with regular expressions effectively.

Syntax of PHP regex functions

We use delimiters, a pattern, and optional modifiers for making a regular expression string.

$exp = "/codingNinja/i";

Here,

Delimiters - '/'

Pattern - 'codingNinja' ( being serached for )

Modifier - 'i' ( make searchign case sensitive )

We can also have delimiters that are not letters, numbers, backslash, or spaces. Forward slash ('/') is the most common delimiter.

Functions of Regular expression in PHP

For using a regular expression, PHP provides us with various functions. the most used functions are 

preg_match() 

This function returns one if we find the pattern in the string provided and 0 if not.

  • PHP

PHP

<?php
echo "<h2> Coding Ninja </h2></br>";
$str = "Visit CodingNinja";
$pattern = "/CodingNinja/i";
echo preg_match($pattern, $str); // Output 1
?>
You can also try this code with Online PHP Compiler
Run Code

Output-

preg_match_all() 

It finds the number of times the pattern occurs in the string ( can be 0 too ).

  • PHP

PHP

<?php
echo "<h2> Coding Ninja </h2></br>";
$str = "The rain in SPAIN falls.";
$pattern = "/ain/i";
echo preg_match_all($pattern, $str);
?>
You can also try this code with Online PHP Compiler
Run Code

Output-

preg_replace()

This function returns a new string where the matched pattern is replaced with another string.

  • PHP

PHP

<?php
echo "<h2> Coding Ninja </h2></br>";
$str = "Visit google!";
$pattern = "/google/i";
echo preg_replace($pattern, "Coding Ninja", $str);
?>
You can also try this code with Online PHP Compiler
Run Code

Output-

Some more regex functions available in PHP are -

Functions Descriptions 
preg_filter()If matches are found, this function would return a string or array that replaces the matched pattern.
preg_last_error()When the most recent regular expression call fails it returns the error code.
preg_replace_callback()The substring returned by the callback replaces the matched pattern of the PHP regex expression; it returns a string.
preg_split()The use of matches of a regular expression as separators breaks the strings into an array.

 

PHP Regular Expression Modifiers

Modifier Description 
iThis modifier performs a case-sensitive search.
mA multiline search is performed by this modifier(patterns that search for the beginning or end of a string that will match the beginning or end of each line)
uThis modifier enables UTF-8 encoded pattern's correct matching.

 

Grouping in PHP 

For applying quantifiers to the entire pattern, we use parenthesis '(),' which may also be used to choose parts of the pattern to use as a match.

  • PHP

PHP

<?php
echo "<h2> Coding Ninja </h2></br>";
$str = "Apples and bananas.";
$pattern = "/ba(na){2}/i";
echo preg_match($pattern, $str);
?>
You can also try this code with Online PHP Compiler
Run Code

Output-

Quantifiers in PHP

We use quantifiers in PHP to define the quantities.

QuantifierDescription
n+The string is containing at least one 'n' gets matched.
n*The string containing zero or more occurrences of 'n' gets matched.
n?The string containing zero or one occurrence of ‘n’ gets matched.
n{x}The string containing the sequence of ‘x’ no. of n's gets matched.
n{x,y}The string containing the 'x' sequence to 'y' no. of n's gets matched.
n{x,}The string containing the sequence of at least ‘x’ no. of n's gets matched.

Advantages of PHP regex Function

  • Powerful Pattern Matching: Allows for complex searches and validations within strings.
  • Versatility: Can be used for a variety of tasks, including data extraction, replacement, and validation.
  • Efficiency: Processes large amounts of text quickly.
  • Flexibility: Supports a wide range of patterns and modifiers.

Frequently Asked Questions

What is an example of a regular expression?

An example of a regular expression is ^\d{3}-\d{2}-\d{4}$, which matches a Social Security Number format (e.g., 123-45-6789). It ensures that the string consists of three digits, a hyphen, two digits, another hyphen, and four digits.

How to test regex in PHP?

To test regex in PHP, use the preg_match() function. This function takes a pattern and a string as arguments, returning 1 if the pattern matches, 0 if it doesn’t, and false if an error occurs. Example: preg_match('/pattern/', $string).

How to validate a regular expression in PHP?

To validate a regular expression in PHP, use the preg_match() function to check if a given string conforms to the specified regex pattern. If the function returns 1, the string is valid; otherwise, it's invalid. Example: preg_match('/^pattern$/', $string).

How to check if a string matches regex in PHP?

To check if a string matches a regex in PHP, use the preg_match() function. Pass the regex pattern and the target string as arguments. It returns 1 for a match, 0 for no match, or false for an error. Example: preg_match('/regex/', $string).

Conclusion

In this blog, we learned about Regular Expressions in PHP. Regular expressions in PHP are a vital tool for developers, enabling efficient string manipulation, validation, and data extraction. By mastering regex patterns and functions, you can enhance your PHP applications' functionality and reliability. Whether you're validating user input or parsing complex strings, leveraging regex will streamline your coding process and improve overall performance.

Check out our PHP Interview questions: Part 1

Live masterclass