Home »
PHP »
PHP programs
PHP program to demonstrate the quantifiers in pattern to search a string using a regular expression
Here, we are going to demonstrate the quantifiers in pattern to search a string using a regular expression in PHP.
Submitted by Nidhi, on November 23, 2020 [Last updated : March 13, 2023]
In this program, we will demonstrate the quantifiers in pattern to search a string using a regular expression, here we will use the preg_replace() function.
Quantifiers in pattern to search a string using a regular expression in PHP
The source code to demonstrate the quantifiers in pattern to search a string using regular expression is given below. The given program is compiled and executed successfully.
<?php
//PHP program to demonstrate the quantifiers in
//pattern to search a string using a regular expression.
$str = "There are five bananas in the bucket";
$pattern = "/ba(na){2}/i";
if (preg_match($pattern, $str) == 1)
printf("Found");
else
printf("Not Found");
?>
Output
Found
Explanation
In the above program, we created a string variable $str, which is initialized with "There are five bananas in the bucket".
$pattern = "/ba(na){2}/i";
In the above code, we used quantifiers in pattern to search a string "banana" by looking for "ba" followed by two instances of "na".
if(preg_match($pattern, $str)==1)
printf("Found");
else
printf("Not Found");
In the above code, we checked the return value of the preg_match() function and then print the appropriate message on the webpage.
PHP Regular Expressions Programs »