Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

html
css
php

What are regular expressions in PHP?

Behzad Ahmad

Overview

Regular expressions are a sequence of characters that are used to form some sort of search pattern. If we want to search for some data in the text, we can use this search pattern to search for it.

A regular expression could be a single character or a sequence of many characters. They are used to perform text searching or replace operations.

Syntax

Regular expressions are composed of delimiters, some patterns, and other optional modifiers.

$exp = "/educative/i";

In this syntax, / is the delimiter, educative is the pattern we want to search, and i is the word used to make the search case-insensitive.

Note: A delimiter can be any character, but it is not a letter, number, space, or a backslash. Forward slash (/) is the most common delimiter.

Regular expression functions

We can use many functions to use regular expressions, but three of them are most commonly used:

  • preg_match()

  • preg_match_all()

  • preg_replace()

The preg_match() function

The preg_match() function allows us to search for a particular word in a string. It returns 1 if the word is found. If the word is not found in the string, it returns 0.

Example

<?php
$line = "Educative";
$word = "/educative/i";
echo preg_match($word, $line);
?>

Explanation

  • Line 2: We make a string and write a message in it.

  • Line 3: We make a string and write the words we want to search in the string.

  • Line 4: We pass the arguments to the function to find the word in the string.

The preg_match_all() function

The preg_match_all() function is used to check the number of times a word appears in a given string. It returns the number of times a word is found in the string.

<?php
$line = "Regular expressions are the sequence";
$word = "/ar/i";
echo preg_match_all($word, $line); 
?>

Explanation

  • Line 2: We make a string and write a message in it.

  • Line 3: We make a string and write the words we want to search in the string.

  • Line 4: We pass the arguments to the function to find the count of words in the string.

The preg_replace() function

The preg_replace() function is used to replace all the matches of the given string with another string. It returns the newly updated string.

<?php
$line = "Welcome to Educative";
$word = "/Educative/i";
echo preg_replace($word, "Mcdonalds", $line);
?>

Explanation

  • Line 2: We make a string and write some message in it.

  • Line 3: We make a string and write some words we want to search in the string.

  • Line 4: We pass the arguments to the function to replace the word in the string.

RELATED TAGS

html
css
php
RELATED COURSES

View all Courses

Keep Exploring