Hey guys, One more tutorial for php. We will build a simple PHP application for replacing any keyword (Word) from particular text with our desired word.It’s not easy,but yeah you have to apply your mind to make it.

What the purpose of search and replace application?

You all know about it, Right! Well we have seen that most of the text editors have this option available. Suppose there is one word “good” in one document.,and it repeats around 20-25 times in a document. Now we want to replace that word with “better”. So it will take more time to replace it individually. Most of the text editors and word applications have directly available option for it. You just have to tell them the word that you want to replace it via other word.



Let me go to the source code.

Code of search and replace application in php

<?php
$offset=0;
if(isset($_POST['text'])&&($_POST['searchfor'])&&($_POST['replacewith']))
{
$text=$_POST['text'];
$search=$_POST['searchfor'];
$replace=$_POST['replacewith'];
$search_length=strlen($search);

if(!empty($text)&&!empty($search)&&!empty($replace))
{
while($strpos=strpos($text,$search,$offset))
{
$offset=$strpos+$search_length;
$text=substr_replace($text,$replace,$strpos,$search_length);

}
echo $text;
}
}
else
{
echo "Fill the data";
}

?> 
  <form action="replaceapp.php" method="POST">
<textarea name="text" rows="7" cols="29" ></textarea>
<br>
<br>
<strong>Search For:</strong>
<br>
<input type="text" name="searchfor">
<br>
<strong>Replace with:</strong>
</br>
<input type="text" name="replacewith">
<br>
<br>
<input type="submit" value="Regenerate">
</form>


Output for search and replace application program





Logic behind this php application

Well first of all you have to design basic form which contains three elements. One if where we write/paste our main text and other two are for search and replace. So now the question arrives how that will work? So first of all you have to declare these elements content into php variables. Then you have to check whether they are empty or not. If not then have to proceed further . We have used strpos function to find the position of the word that you want to replace.I hope you like this search and replace application. If you have any other doubts then simply comment here. I will surely help you within 24 hours. Enjoy coding.

By jigar

Leave a Reply

Your email address will not be published. Required fields are marked *