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

$length = strlen($search);

if (!empty($_POST['text'])&& !empty($_POST['searchfor'])&&!empty($_POST['replacewith']))
{
while ($stringpos = strpos($text, $search, $offset)) 
{
$offset = $stringpos + $length;
$text = substr_replace($text, $replace, $stringpos, $length);
}
echo $text;
}
else
{
echo 'Please fill in all the fields';
}

}

?>

<form action=53fineandreplace.php method="POST">
<textarea name = "text" rows="6" cols = "30"></textarea><br><br>
Search For:<br>
<input type= "text" name = "searchfor"><br><br>
Replace with:<br>
<input type="text" name = "replacewith"><br><br>
<input type = "submit" value = "Submit">
</form>

If the word to be replaced is the first word or the only word in the string then it doesn't work but if the word to be replaced is in any other position except the first then it works fine.

3 Answers 3

1

strpos returns the position the needle ($search) is found in the haystack ($text). If it's found at the beginning of the it, strpos will return 0, which PHP treats as false, and thus terminate the while loop without even entering it. One way to solve this is to use the !== operator to distinguish between a boolean FALSE and an integer 0:

while (!($stringpos = strpos($text, $search, $offset)) !== FALSE)
Sign up to request clarification or add additional context in comments.

Comments

0

You can use below php function str_replace and achieve it easily

Syntax

str_replace(find,replace,string,count)

find -> It is required field.Specifies the value to find

replace -> It is required field.Specifies the value to replace the value in find

string -> It is required field.Specifies the string to be searched

count -> It is Optional field.A variable that counts the number of replacements

Comments

0

you should just use the do while loop because it will execute at least once but you need to make the variable in the first if statement just like this

if (isset($_POST['text']) && isset($_POST['replace_what']) && isset($_POST['replace_with'])){
  $text=$_POST['text'];
  $search=$_POST['replace_what'];
  $replace=$_POST['replace_with'];
  $string_length=strlen($search);
  $offset=0;
  $strpos=0;
  if (!empty($text) && !empty($search) && !empty($replace)) {


    do{
      $offset= $strpos + $string_length;
      $text=substr_replace($text,$replace,$strpos,$string_length);




    }while ($strpos= strpos($text,$search,$offset));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.