Wednesday, March 21, 2012

Find and Replace Application in php using strlen();, strpos();, & substr_replace(); functions


<?php
$offset = 0;
if(isset($_POST['text'])&& isset($_POST['find'])&& isset($_POST['replace'])) {
 $text = $_POST['text'];
 $find = $_POST['find'];
 $replace = $_POST['replace'];

  $find_len = strlen($find);

       if(!empty($text) && !empty($find) && !empty($replace)) {
 
      while($strpos = strpos($text, $find, $offset)) {
   $offset = $strpos + $find_len;
$text = substr_replace($text, $replace, $strpos, $find_len);
}
        echo $text;
 
  } else {
  echo 'please fill in all fields';
  }
}

?>
<form action="app3.php" method="post">
<textarea name="text" rows="7" cols="30"></textarea></br></br>
Search for:</br>
<input type="text" name="find"></br></br>
Replace with:</br>
<input type="text" name="replace"></br></br>
<input type="submit" value="Find & Replace">
</form>

No comments:

Post a Comment