Find and Replace Application in PHP
In Windows Notepad There is Feature of Find and Replace a Text With the Another Text.Similarly Here In this Tutorial We also Create a Find and Replace Application in PHP. For Making This We Use Some Built in Functions In PHP Like.
- strpos() – Finding the String Position.
- strlen() – Finding the String Length.
- substr_replace() – Replacing a Specific String.
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
<?php $offset =0; // Setting Offset Value For String. if(isset($_POST['text']) && isset($_POST['searchfor']) && isset($_POST['replacewith'])) { $text = $_POST['text']; //Getting Text Area Value In Which String Is Entered $search = $_POST['searchfor']; // Getting String To Be Searched $replace =$_POST['replacewith'];// Getting String To Be Replace with $search_length = strlen($search);// Getting String length if(!empty($text)&&!empty($search)&&!empty($replace)) //Checking Value is Empty or Not { while($strpos = strpos($text,$search,$offset)) //Finding The Search String With While Loop { $offset = $strpos + $search_length;//Changing Offset value $text = substr_replace($text, $replace,$strpos,$search_length);// Here String is Replaced } echo '$text'; } else { echo'Please fill in all fields.'; } } ?> <form action="findandreplace.php" method="POST"> <textarea name="text" rows="6" cols="30"> Search for:<br> <input type="text" name="searchfor"><br><br> Replace with:<br> <input type="text" name="replacewith"><br><br> <input type="submit" value="Find and Replace"> </form> |
<?php $offset =0; // Setting Offset Value For String. if(isset($_POST['text']) && isset($_POST['searchfor']) && isset($_POST['replacewith'])) { $text = $_POST['text']; //Getting Text Area Value In Which String Is Entered $search = $_POST['searchfor']; // Getting String To Be Searched $replace =$_POST['replacewith'];// Getting String To Be Replace with $search_length = strlen($search);// Getting String length if(!empty($text)&&!empty($search)&&!empty($replace)) //Checking Value is Empty or Not { while($strpos = strpos($text,$search,$offset)) //Finding The Search String With While Loop { $offset = $strpos + $search_length;//Changing Offset value $text = substr_replace($text, $replace,$strpos,$search_length);// Here String is Replaced } echo '$text'; } else { echo'Please fill in all fields.'; } } ?> <form action="findandreplace.php" method="POST"> <textarea name="text" rows="6" cols="30"> Search for:<br> <input type="text" name="searchfor"><br><br> Replace with:<br> <input type="text" name="replacewith"><br><br> <input type="submit" value="Find and Replace"> </form>