Implementing find and replace functionality in PHP

1
4135

In this session today we will be implementing find and replace functionality in php.Here we will be creating a form which will have an text area , search box , replace box and an find and replace button .

  • For implementing find and replace functionality in php follow the steps given below :

  1. First of all download and install xampp server in your machine .
  2. Let’s begin with creating a form .
  3. Go to Start->All Programs->XAMPP->XAMPP htdocs folder as shown below in the image ..

  4. In htdocs folder create a new folder and lets name the folder as search.

  5. Inside the search folder create a new file say index.php.

  6. Open the index.php file with any text editor for example Notepad++ and write the following code for the form creation:
  7. Here is the screen shot of the code :
  8. Now open up your browser and enter the following url http://localhost/Search/
  9. Thus you will have the following output :

  10. Now let’s write the logic for find and replace .
  11. Now in the same index.php file add the following code.
  12. Here is the screen shot for it :

  13. Now inside if statement take three variables which will store the values from the post variable and also perform validation checks on it.
  14. Here is the screen shot for it..

  15. So now if you run your programme and forget to fill any of the field it will pop-up an message which will say ” Please fill all the fields “.

  16. Now take two variable :
  17. Here is the screen shot of the code :

  18. Now let’s take one while loop inside the nested if statements so add the code as follows :
  19. Screen shot is shown below :

  20. Now add function to replace the string which is found
  21. Screen shot is given below :

  22. Now add the following line of code after the while loop to display the string in the replaced version.
  23. Here is the screen shot for it :

  24. Now here is the complete code for implementing find and replace functionality in php .
  25. Now open up the browser and enter the following url localhost/Search/index.php and you will have the following output :

  26. Now type the Following text in your text area as follows Android is used by Apple
  27. Corresponding to your search field write Apple
  28. Corresponding to your replace field write Google
  29. After filling up the respective fields you will have the following view of your window:

  30. So now when you click on the find and replace button you will see the following output :

  31. Thus ,we have successfully learnt implementing find and replace functionality in php.

1 COMMENT

  1. Hey man. Great tutorial, but i seem to be stuck on something. How would you go about finding and replacing several strings in the text? I really appreciate your help buddy!

LEAVE A REPLY

Please enter your comment!
Please enter your name here