PHP program to replace one string using another string in php

Write a PHP program to replace one string using another string.


In this tutorial, you will learn how to replace one string using another string in php.

Below is the php script to replace one string using another string in php.

<html>
<head>
    <title>PHP program to replace one string using another string</title>
</head>
<body>

    <h2>Write a PHP program to replace one string using another string</h2>

    <form action="" method="POST">
        <input type="text" name="str" placeholder="enter the string here"/></br>
        <input type="text" name="fstr" placeholder=" Enter the string to be found"/></br>
        <input type="text" name="rstr" placeholder=" enter the string to be replaced"/></br>
        <input type="submit"/></br>
    </form>

    <?php
        if($_POST)
        {
            $str = $_POST['str'];
            $fstr = $_POST['fstr'];
            $rstr = $_POST['rstr'];
     
            $new_string = str_replace($fstr, $rstr, $str);
           
            if($new_string!=$str)
            {
                echo "The given string is $str </br>";
                echo "The replaced string is $new_string";
            }
            else
            {
                echo "Couldn't Replace";
            }
        }
    ?>

</body>
</html>


Thanks for reading.