PHP program to demonstrate the regular expression to replace the substring within the string

Here, we are going to demonstrate the regular expression to replace the substring within the string in PHP.
Submitted by Nidhi, on November 23, 2020 [Last updated : March 13, 2023]

In this program, we will demonstrate the regular expression to replace a specified substring within the string using the preg_replace() function.

Regular expression to replace the substring within the string in PHP

The source code to demonstrate the regular expression to replace the substring within the string is given below. The given program is compiled and executed successfully.

<?php
//PHP program to demonstrate the regular expression 
//to replace the substring within the string.

$str = "Welcome to India";
$pattern = "/india/i";

$str1 = preg_replace($pattern, "USA", $str);

print ($str1);
?>

Output

Welcome to USA

Explanation

In the above program, we created a string variable $str, which is initialized with "Welcome to India". After that, we used 'i' in the pattern to search case insensitive substring in the specified string. Here, we used the preg_replace() function to replace the substring within the string and return the updated string that will be assigned to the variable $str1 and printed on the webpage using the print() function.

PHP Regular Expressions Programs »





All PHP Programs

Comments and Discussions!

Load comments ↻





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