PHP program to check a substring exists within the given string using a regular expression pattern

Here, we are going to learn how to check a substring exists within the given string using a regular expression pattern in PHP?
Submitted by Nidhi, on November 23, 2020 [Last updated : March 13, 2023]

In this program, we will perform regular expression pattern matching using the preg_match() function, here we checked a substring is exist in the specified string or not.

Check a substring exists within the given string using a regular expression pattern in PHP

The source code to check a sub-string exists within the given string using a regular expression pattern is given below. The given program is compiled and executed successfully.

<?php
//PHP program to check a substring is exists 
//within the given string using regular expression pattern.
$str = "www.includehelp.com";
$pattern = "/includehelp/";

$res = preg_match($pattern, $str);

if ($res == 1)
{
    printf("Substring found successfully");
}
else
{
    printf("Substring did not find in the string");
}
?>

Output

Substring found successfully

Explanation

Here, we created a string variable $str, which is initialized with "www.includehelp.com". After that, we used a pattern to search substring in the specified string. Here we used the preg_match() function that will return 1 on a successful match, otherwise, it will return 0. Then we used the if condition to print the appropriate message on the webpage.

PHP Regular Expressions Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.