Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
PHP regex functions 
3.
Regular Expression Modifiers
4.
Grouping
5.
Quantifiers
6.
Frequently Asked Questions
7.
Key Takeaways
Last Updated: Mar 27, 2024

PHP regex

Introduction

A sequence of characters that forms a search pattern is called regular expression. While searching or validating the format of any input field, for example, email, we use regular expressions. These can be complicated patterns or a single character.

Syntax:

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

$exp = "/codingNinja/i";
You can also try this code with Online PHP Compiler
Run Code

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.

PHP regex functions 

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
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
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
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.

 

Regular Expression Modifiers

Modifier  Description 
i This modifier performs a case-sensitive search.
m A 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)
u This modifier enables UTF-8 encoded pattern's correct matching.

 

Grouping

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
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

We use quantifiers in PHP to define the quantities.

Quantifier Description
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.

 

Frequently Asked Questions

1. Explain metacharacters with some examples.

The characters with special meanings are called metacharacters.

Some examples of metacharacters are:-

  • | ( finds a match for any one of the patterns separated by | )
  • . (this metacharacter finds one instance of any character)
  • ^ ( beginning of the string is matched with the use of this character)
  • \d ( finds a digit)
  • $ ( end of the string is matched such as word$ )
  • \s ( Look for a whitespace character )
  • \b ( Find a match at the beginning of a word, such as \bWORD, or the end of a word, such as WORD\b )
  • \uxxxx (the hexadecimal number xxxx is provided fr finding Unicode characters )

 

2. Describe the regular expression patterns and give some examples.

For finding a range of characters, we use brackets in regular expression patterns.

Some examples of regular expression patterns are-

  • [abc] - this means finding one character given within the brackets.
  • [^abc] - this means finding any character not present between the brackets.
  • [0-9] - this means finding a number between 0 to 9 

Key Takeaways

In this blog, we learned about PHP regex. Don't come to a halt here. Check out our PHP Interview questions: Part 1 | Coding Ninjas Blog. Can you also check out the Why Use PHP programming in 2021? Its Pros and Cons | Coding Ninjas Blog blog. Check out more blogs, including types of software testing, security testing, etc., here. More blogs.

Happy Learning!

Live masterclass