ADVERTISEMENT
ADVERTISEMENT

PHP program to demonstrate the regular expression to count the occurrence of given substring

Here, we are going to demonstrate the regular expression to count the occurrence of given substring in PHP.
Submitted by Nidhi, on November 23, 2020

In this program, we will demonstrate the regular expression to count the total number of occurrences of a specified substring within the string using the preg_match_all() function.

Program/Source Code:

The source code to demonstrate the regular expression to count the occurrence of a given substring is given below. The given program is compiled and executed successfully.

<?php
//PHP program to demonstrate the regular expression 
//to count the occurrence of given substring.

$str = "India is a country located in asia";
$pattern = "/in/i";

$count = preg_match_all($pattern, $str);

printf("Total occurrences of are: %d", $count);
?>

Output:

Total occurrences of are: 2

Explanation:

In the above program, we created a string variable $str, which is initialized with "India is a country located in Asia". After that, we used 'i' in the pattern to search case insensitive substring in the specified string. Here we used the preg_match_all() function that will return the total number of occurrences of a specified substring within the string that will be assigned to the variable $count and printed on the webpage using printf() function.

PHP Regular Expressions Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions


ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.