PHP Program to replace word in a string using str_replace() function

How to replace the word in a string using PHP?

In this program, we are replacing the word in the previously entered string. To do so we are using the built-in function str_replace(). For this, we first have to assign the string into the variable string then assign the word which should be replaced to the variable w and assign the string which is replaced to the variable r. After that to replace the word in the string using the built-in function str_replace(w,r, string) and at last print the value of the variable string

Syntax of function str_replace()


str_replace(find,replace,string,count)
 

ALGORITHM

Step 1: Assign the string into the variable string

Step 2: Assign the word which should be replaced to the variable w

Step 3: Assign the string which is replace to the variable r

Step 4: To replace the word in the string use the built-in function str_replace(w,r,string)

Step 5: Print the value of the variable string

PHP Source Code

                                          <?php
$string = "learnetutorials.com";
$w = "learn";
$r = "LEARN";
echo "The original string: $string \n";
$string = str_replace($w, $r, $string);
echo "String after change: $string";
?>
                                      

OUTPUT

The original string: learnetutorials.com
String after change: LEARNetutorials.com